View Single Post
Old 06-25-2009, 07:58 PM   #6 (permalink)
Wildhoney
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

It's a good job I am in the mood for arrays !

We can then modify the two functions a little bit to accommodate for arrays to be passed in. It will still work the same as before if you want to remove a single item. However, we now have the ability to remove multiple indexes by passing in an array of the values to be removed.

Although before we could have just repeated the call to array_drop_* many times.

array_drop_multiple

php Code:
/**
 * Example: Removes all the "Apples" from the array.
 *    array('Oranges', 'Apples', 'Apples');
 *    (This will leave only "Oranges".)
 *
 * @return void
 * @param mixed $szSearch
 * @param array $aArray
 */

function array_drop_multiple($mSearch, &$aArray)
{
    if (!is_array($mSearch))
    {
        $mSearch = (array) $mSearch;
    }
   
    foreach ($mSearch as $szSearch)
    {
        while (($iKey = array_search($szSearch, $aArray)) !== false)
        {
            unset($aArray[$iKey]);
        }
    }
}

array_drop_single

php Code:
/**
 * Example: Removes only the first "Apples" it locates.
 *
 * @return void
 * @param mixed $szSearch
 * @param array $aArray
 */

function array_drop_single($mSearch, &$aArray)
{
    if (!is_array($mSearch))
    {
        $mSearch = (array) $mSearch;
    }
   
    foreach ($mSearch as $szSearch)
    {
        $iKey = array_search($szSearch, $aArray);
        unset($aArray[$iKey]);
    }
}

Then to use the functions, in this case I am using the array_drop_multiple function as the example:

php Code:
$aFruits = array('Oranges', 'Apples', 'Pears', 'Bananas', 'Apples');

/* Let's shuffle the array so we can't cheat. */
shuffle($aFruits);

/* Drop an item array based on its value. */
array_drop_multiple(array('Apples', 'Bananas'), $aFruits);

/* Let's see if it's gone... */
print_r($aFruits);

/* ...Has it? */

Result:

Quote:
Array
(
[3] => Oranges
[4] => Pears
)
Notice the array being passed in at the first argument is now an array. This removes multiple items. Although we can still pass in a single item, like so:

php Code:
/* Drop an item array based on its value. */
array_drop_multiple('Apples', $aFruits);
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote