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?)
}
}
}
}
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.
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.
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]);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With