Last active
February 23, 2023 03:22
-
-
Save jeankassio/841d1e71f28dc8175b14a3ff5ad804fb to your computer and use it in GitHub Desktop.
PHP - search and remove any index of multidimensional array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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