View Single Post
Old 06-25-2009, 07:11 PM   #4 (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

I wrote the following two functions, without knowing what you want precisely, admittedly, but I had a sudden urge to write them!

The first of the two functions is the most simply of them, and will remove only the first instance of "Apples" it finds. The second function will remove every single "Apples" instance it can possibly find in the array.

I am posting both, and not combining them into one function, so that you're able to easily under the most basic of the two functions: array_drop_single

array_drop_single

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

function array_drop_single($szSearch, &$aArray)
{
    $iKey = array_search($szSearch, $aArray);
    unset($aArray[$iKey]);
}

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 string $szSearch
 * @param array $aArray
 */

function array_drop_multiple($szSearch, &$aArray)
{
    while (($iKey = array_search($szSearch, $aArray)) !== false)
    {
        unset($aArray[$iKey]);
    }
}

However, ignoring the latter of the two functions, this is how you would interact with array_drop_single. The array is passed as reference, and so is changed literally inside the function itself. There is no return value in either of the functions.

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

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

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

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

/* ...Has it? */
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.

Last edited by Wildhoney : 06-25-2009 at 07:33 PM.
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
The Following User Says Thank You to Wildhoney For This Useful Post:
tech (06-25-2009)