Jonas Kaufmann Jonas Kaufmann - 3 months ago 13
PHP Question

Recursively remove element by value

So I have the following array:

$array = array(array('fruit1' => 'apple'),
array('fruit2' => 'orange'),
array('veg1' => 'tomato'),
array('veg2' => 'carrot'));


and I want to run a function like this:

array_remove_recursive($array, 'tomato');


so the output is this:

$array = array(array('fruit1' => 'apple'),
array('fruit2' => 'orange'),
array('veg2' => 'carrot')); // note: the entire array containing tomato has been removed!


Is this solvable?

Answer
function array_remove_recursive($getArray,$getAssocValue)
{
    $returnArray    = array();
    if(is_array($getArray))
    {
        foreach($getArray as $indAssocValue)
        {
            if(is_array($indAssocValue))
            {
                foreach($indAssocValue as $innerKey=>$innerVal)
                {
                    if($innerVal!=$getAssocValue and $innerKey!="")
                    {
                        $returnArray[]  = array("$innerKey"=>$innerVal);
                    }
                }
            }
        }
    }
    return $returnArray;
}

$array = array(array('fruit1' => 'apple'), 
               array('fruit2' => 'orange'), 
               array('veg1' => 'tomato'), 
               array('veg2' => 'carrot'));
               print_r($array);
               echo "<br />";
$array  = array_remove_recursive($array, 'tomato');
print_r($array);

hope the above code would be helpfull.