PHP.nl

array_walk

array_walk

Apply a user supplied function to every member of an array

true **array_walk**  $array callable $callback mixed $arg

Applies the user-defined function to each element of the array. callback``array

is not affected by the internal array

pointer of .
will walk through the entire array regardless of pointer position. array_walk``array``array_walk

arrayThe input array.

callback Typically, takes on two parameters. The parameter's value being the first, and the key/index second. callback``array

Opmerking: > If needs to be working with the actual values of the array, specify the first parameter of as a . Then, any changes made to those elements will be made in the original array itself. callback``callbackreference

Opmerking: > Many internal functions (for example ) will throw if more than the expected number of arguments are passed in and are not usable directly as a . strtolower``callback

   Only the values of the  may potentially be
   changed; its structure cannot be altered, i.e., the programmer cannot
   add, unset or reorder elements. If the callback does not respect this
   requirement, the behavior of this function is undefined, and      
   unpredictable.
  `array`

arg If the optional parameter is supplied, it will be passed as the third parameter to the . arg``callback

return.true.always

As of PHP 7.1.0, an will be thrown if the function requires more than 2 parameters (the value and key of the array member), or more than 3 parameters if the is also passed. Previously, in this case an error of level would be generated each time calls . ArgumentCountError``callback``argE_WARNINGarray_walk``callback

Voorbeeld: example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?>
Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple

Voorbeeld: example using anonymous function

<?php
$elements = ['a', 'b', 'c'];

array_walk($elements, function ($value, $key) {
  echo "{$key} => {$value}\n";
});

?>
0 => a
1 => b
2 => c

array_walk_recursive``iterator_apply``list``each``call_user_func_array``array_map