I've made this function and work pretty great.
function erase(array &$arr, array $children)
{
$ref = &$arr;
foreach ($children as $child)
if (is_array($ref) && array_key_exists($child, $ref)) {
$toUnset = &$ref;
$ref = &$ref[$child];
} else
throw new Exception('Path does\'nt exist');
unset($toUnset[end($children)]);
}
Example 1:
Here's an example of how you would unset $arr['session']['session3']['nestedSession2']
$arr = [
"system" => [
"system1" => "value1",
"system2" => "value2"
],
"session" => [
"session1" => "value3",
"session2" => "value4",
"session3" => [
"nestedSession1" => "value5",
"nestedSession2" => "value6",
],
],
];
print_r($arr);
erase($arr, array('session', 'session3', 'nestedSession2'));
print_r($arr);
Example 2:
It can even unset a whole nested array, here's how you would do it (handling errors):
print_r($arr);
try {
erase($arr, array('session', 'session3'));
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
print_r($arr);
Example 3:
It also work with non-assiociative array:
$arr = array('fruit1', 'fruit2', 'fruit3');
print_r($arr);
try {
erase($arr, array(0));
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
print_r($arr);
Example 4:
In case of error:
$arr = array('fruit1', 'fruit2', 'fruit3');
print_r($arr);
try {
erase($arr, array('pathThatDoesNotExit'));
} catch (Exception $e) {
// do what you got to do here in case of error (if the path you gave doesn't exist)!
echo 'Caught exception: ', $e->getMessage(), "\n";
}
print_r($arr);