Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unset inside array_walk_recursive not working

Tags:

arrays

php

  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?

like image 762
JohnSmith Avatar asked Dec 01 '22 06:12

JohnSmith


2 Answers

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]);
like image 114
dfsq Avatar answered Dec 06 '22 11:12

dfsq


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.

like image 35
NikiC Avatar answered Dec 06 '22 09:12

NikiC