Detailed explanation of php array_walk applying user-defined functions to each element in the array

高洛峰
Release: 2023-03-03 13:48:02
Original
1378 people have browsed it

php array_walk applies a user-defined function to each element in the array

array_walk uses a user-defined function to perform callback processing on each element in the array

Basic syntax

bool array_walk ( array &$array , callable $funcname [, mixed $userdata = NULL ] )

Apply the user-defined function funcname to each cell in the array.

array_walk() is not affected by array's internal array pointer. array_walk() will walk through the entire array regardless of the position of the pointer.

Parameter introduction:

Detailed explanation of php array_walk applying user-defined functions to each element in the array

Description:

1.array_walk() function applies a callback function to each element in the array. Returns TRUE if successful, FALSE otherwise.

2. Typically funname accepts two parameters. The value of the array parameter is used as the first one, and the key name is used as the second one. If the optional parameter userdata is provided, it will be passed to the callback function as the third parameter.

3. If the funname function requires more parameters than given, an E_WARNING level error will be generated every time array_walk() calls funname. These warnings can be suppressed by preceding the array_walk() call with PHP's error operator @, or by using error_reporting().

4. If the callback function needs to act directly on the values ​​in the array, you can specify the first parameter of the callback function as a reference.

Return Value

Returns TRUE on success, or FALSE on failure.

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 <br />";
}
echo "Before ...:<br />";
array_walk($fruits, &#39;test_print&#39;);
array_walk($fruits, &#39;test_alter&#39;, &#39;fruit&#39;);
echo "... and after:<br />";
array_walk($fruits, &#39;test_print&#39;);
?>
Copy after login

Running result:

Before ...:
d . lemon
a . orange
b . banana
c . apple
... and after:
d . fruit : lemon
a . fruit : orange
b . fruit : banana
c . fruit : apple


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!