7
  array_walk_recursive($arr, function(&$val, $key){
    if($val == 'smth'){
      unset($val);          // <- not working, unset($key) doesn't either
      $var = null;          // <- setting it to null works
    }
  });

  print_r($arr);

I don't want it to be null, I want the element out of the array completely. Is this even possible with array_walk_recursive?

1

3 Answers 3

16

You can't use array_walk_recursive here but you can write your own function. It's easy:

function array_unset_recursive(&$array, $remove) {
    $remove = (array)$remove;
    foreach ($array as $key => &$value) {
        if (in_array($value, $remove)) {
            unset($array[$key]);
        } elseif (is_array($value)) {
            array_unset_recursive($value, $remove);
        }
    }
}

And usage:

array_unset_recursive($arr, 'smth');

or remove several values:

array_unset_recursive($arr, ['smth', 51]);
Sign up to request clarification or add additional context in comments.

Comments

5

unset($val) will only remove the local $val variable.

There is no (sane) way how you can remove an element from the array inside array_walk_recursive. You probably will have to write a custom recursive function to do so.

2 Comments

I thought of that, but what if the array has more than 2 levels?
@JohnSmith Just noticed that too :(
2

The answer of @dfsq is correct but this function doesn't remove empty array. So you can end up with Tree of empty array, which is not what is expected in most cases. I used this modified function instead:

public function array_unset_recursive(&$array, $remove) {
    foreach ($array as $key => &$value) {
        if (is_array($value)) {
            $arraySize = $this->array_unset_recursive($value, $remove);
            if (!$arraySize) {
                unset($array[$key]);
            }
        } else if (in_array($key, $remove, true)){
            unset($array[$key]);
        }
    }
    return count($array);
}

Comments

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.