note 114574 modified in function.array-walk-recursive by frozenfire

From: Date: Fri, 07 Mar 2014 22:58:30 +0000
Subject: note 114574 modified in function.array-walk-recursive by frozenfire
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-198827@lists.php.net to get a copy of this message
array_walk_recursive itself cannot unset values. Even though you can pass array by reference, unsetting the value in the callback will only unset the variable in that scope. <?php /** * http://uk1.php.net/array_walk_recursive implementation that is used to remove nodes from the array. * * @param array The input array. * @param callable $callback Function must return boolean value indicating whether to remove the node. * @return array */ function walk_recursive_remove (array $array, callable $callback) { foreach ($array as $k => $v) { if (is_array($v)) { $array[$k] = walk_recursive_remove($v, $callback); } else { if ($callback($v, $k)) { unset($array[$k]); } } } return $array; } ?> An up to date implementation of the above function can be looked up from https://github.com/gajus/marray/blob/master/src/marray.php#L116. --was-- array_walk_recursive itself cannot unset values. Even though you can pass array by reference, unsetting the value in the callback will only unset the variable in that scope. <?php /** * http://uk1.php.net/array_walk_recursive implementation that is used to remove nodes from the array. * * @param array The input array. * @param callable $callback Function must return boolean value indicating whether to remove the node. * @return array */ function walk_recursive_remove (array $array, callable $callback) { foreach ($array as $k => $v) { if (is_array($v)) { $v = walk_recursive_remove($v, $callback); } else { if ($callback($v, $k)) { unset($array[$k]); } } } return $array; } ?> An up to date implementation of the above function can be looked up from https://github.com/gajus/marray/blob/master/src/marray.php#L116. http://php.net/manual/en/function.array-walk-recursive.php

« previous php.notes (#198827) next »