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?
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]);
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With