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);