1

Lets suppose I have this array:

$doc = array(
    'nfe' => array(
        'inf' => array(
            'det' => array(
                'emit' => array(
                     'name' => 'My name'
                )
            )
        )
    )
)

and another array with the keys I want to unset (in order):

$keys = ['nfe', 'inf', 'det', 'emit']

How can I dynamically do this:

unset($doc['nfe']['inf']['det']['emit']);

Based on both arrays $doc and $keys ?

1
  • Have you tried anything so far? Commented Oct 1, 2019 at 18:21

1 Answer 1

3

Playing around with some of my code from How to access and manipulate multi-dimensional array by key names / path?:

function unsetter($path, &$array) {
    $temp =& $array;
    $last = array_pop($path);

    foreach($path as $key) {
        $temp =& $temp[$key];
    }
    unset($temp[$last]);
}

Here is an eval method:

function unsetter($path, &$array) {
    $path = "['" . implode("']['", $path) . "']";
    eval("unset(\$array{$path});");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I would never think of a solution like this. It worked like a charm. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.