Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete element from multi-dimensional array based on key

Tags:

arrays

php

How can I delete an element from a multi-dimensional array given a key?

I am hoping for this to be greedy so that it deletes all elements in an array that match the keys I pass in. I have this so far where I can traverse a multi-dimensional array but I can't unset the key I need to because I don't have a reference to it!

function traverseArray($array, $keys)
{ 
    foreach($array as $key=>$value)
    { 
        if(is_array($value))
        { 
            traverseArray($value); 

        } else {

            if(in_array($key, $keys))
           {                    
                //unset(what goes here?) 

            }

        } 
    }

}
like image 807
Abs Avatar asked Aug 20 '11 21:08

Abs


People also ask

How do you remove an array from a key?

Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.

Can you delete elements from an associative array?

Answer: Use the PHP unset() Function If you want to delete an element from an array you can simply use the unset() function. The following example shows how to delete an element from an associative array and numeric array.


1 Answers

The following code works (and doesn't use deprecated stuff), just tested it:

function traverseArray(&$array, $keys) { 
  foreach ($array as $key => &$value) { 
    if (is_array($value)) { 
      traverseArray($value, $keys); 
    } else {
      if (in_array($key, $keys)){
        unset($array[$key]);
      }
    } 
  }
}
like image 173
Marian Galik Avatar answered Sep 22 '22 07:09

Marian Galik