Skip to content

Instantly share code, notes, and snippets.

@jeankassio
Last active February 23, 2023 03:22
Show Gist options
  • Save jeankassio/841d1e71f28dc8175b14a3ff5ad804fb to your computer and use it in GitHub Desktop.
Save jeankassio/841d1e71f28dc8175b14a3ff5ad804fb to your computer and use it in GitHub Desktop.
PHP - search and remove any index of multidimensional array
<?php
function remove_array_key($key, &$array){
$result = array_key_exists($key, $array);
if($result){
unset($array[$key]);
return $array;
}
foreach ($array as &$v){
if(is_array($v)){
$result = remove_array_key($key, $v);
}
if(is_array($result)){
unset($v[$key]);
return $array;
}
}
return false;
}
//USAGE:
$array = array(
'teste1' => "ble",
'teste2' => "lol",
'teste3' => array(
'teste4' => "pop",
'teste5' => array(
'teste6' => "hello"
),
'teste7' => "vesh",
),
'teste8' => "huhu"
);
remove_array_key("teste5", $array);
/*
this print:
array(4) {
["teste1"]=>
string(3) "ble"
["teste2"]=>
string(3) "lol"
["teste3"]=>
array(2) {
["teste4"]=>
string(3) "pop"
["teste7"]=>
string(4) "vesh"
}
["teste8"]=>
string(4) "huhu"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment