1

A bit unusual use-case but maybe you can help:

I have the keys of an value as a separate array. It is pretty easy to get the value of the array with it like this:

function whatEver(){

    $array = array(
        0 => array( 'other' ),
        1 => array(
            0 => array( 'other' ),
            1 => array( 'value' )
        ),
    );

    $keys = array(
        0 => '1',
        1 => '1'
    );

    $result = $array;

    foreach($keys as $key)
    {
        $result = $result[$key];
    }

    return $result;
}

This will return the correct array/value:

Array
(
    [0] => value
)

But what if I want to delete this value (like unset($array[1][1])) from the original array and return the original $array without the value?

7
  • Do you want the Key and the value gone, or just the value? Commented Aug 30, 2018 at 12:30
  • I want the key and the value gone and return the original array without the value. Commented Aug 30, 2018 at 12:31
  • Did unset($array[$key][$key]); fail or something? Commented Aug 30, 2018 at 12:32
  • Check this out: stackoverflow.com/questions/369602/… Commented Aug 30, 2018 at 12:33
  • 1
    $array is dynamic and I don't know the structure. $keys is dynamic, too, and can have an unknown amount of values. That is why I cannot do a simple unset($array[$key][$key]). Otherwise I could also easily get the value without a foreach-loop. So I don't think that this is a duplicate. But please correct me if I am missing something... Commented Aug 30, 2018 at 12:47

2 Answers 2

2

If you need this to work for an arbitrary number of keys, you'll need to assign $result by reference on each iteration, and unset at the final step:

$result = &$array;
$last = array_pop($keys);

foreach ($keys as $key) {
  $result = &$result[$key];
}

unset($result[$last]);

Note that you need to treat the final key slightly differently (the one stored in $last). If you just set a reference down to the last level, the unset will only remove the reference, not the actual element.

See https://3v4l.org/0a5Nv

Sign up to request clarification or add additional context in comments.

Comments

2

Have you tried using the unset($array[$key])? This will delete that key out of the array along with whatever value is associated with it.

This is probably a duplicate of: PHP: Delete an element from an array

1 Comment

the problem is, that both ($array and $key) are dynamic and you don't know the length and structure. If I unset($array[$key])) then I will always delete the key in the first level of the multidimensional array. But it might be in the 10th level, so I need the key path to delete it like array[$key][$key][$key][...] or whatever. This is why I am struggling ... :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.