Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Feb 2005
    Posts
    663
    Thanks
    5
    Thanked 14 Times in 14 Posts

    Add and Remove from Array

    What would be the best way too:

    1. Take and remove a value from a array_1. Then update array_1.
    2. Add the removed value from array_1 to array_2

    I'm doing some google searching and I see a function called array_remval that shows this code. Is that the best approach to removing a value?
    PHP Code:
    function array_remval($val, &$arr)
       {
             
    $array_remval $arr;
             for(
    $x=0;$x<count($array_remval);$x++)
             {
                 
    $i=array_search($val,$array_remval);
                 if (
    is_numeric($i)) {
                     
    $array_temp  array_slice($array_remval0$i );
                   
    $array_temp2 array_slice($array_remval$i+1count($array_remval)-);
                   
    $array_remval array_merge($array_temp$array_temp2);
                 }
             }
             return 
    $array_remval;
       }

    $stack=Array('apple','banana','pear','apple''cherry''apple');
    array_remval("apple"$stack);

    //output: Array('banana','pear', 'cherry') 

  • #2
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    PHP Code:
    <?php
    $remove 
    'apple';
    $stack = array('apple','banana','pear','apple','cherry','apple');
    $removed = array();
    foreach(
    $stack as $k => $v)
    {
        if(
    $v == $remove)
        {
            
    $removed[] = $v;
            unset(
    $stack[$k]);
        }
    }

    echo 
    '<pre>' print_r($stack,1) . print_r($removed,1);
    ?>
    Out of curiosity why do you want an array of the removed items?

  • #3
    Regular Coder
    Join Date
    Feb 2005
    Posts
    663
    Thanks
    5
    Thanked 14 Times in 14 Posts
    Quote Originally Posted by Inigoesdr
    Out of curiosity why do you want an array of the removed items?
    Essentially, I'll have to strings in a table (ie, rows 1 and 2) Perhaps not the best method, but the goal is convert each string into an array. Compare both arrays to variable. If the variable is found in one, than array remove it and add the variable to the other array.

    Then convert both arrays back into strings, and update the table.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •