Home >Backend Development >PHP Tutorial >PHP array function example: array_walk()

PHP array function example: array_walk()

WBOY
WBOYOriginal
2023-06-20 08:06:101292browse

PHP is a scripting language suitable for writing Web applications. You can easily create dynamic Web pages using PHP. PHP provides a large number of array functions, array_walk() is one of the very useful functions.

The array_walk() function can run a user-defined function on each element of the array. This function will call a user-defined callback function and pass the parameters to each array element to implement the array traversal operation. The syntax of the array_walk() function is as follows:

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

The parameters of this function include:

  • $array: the array to be traversed;
  • $callback: A callback function that needs to be applied to the array element. This function accepts two parameters:

    • $value: the value of the array element;
    • $key: the key of the array element;
  • $userdata: Optional parameters, parameters passed to the callback function.

Next we use an example to demonstrate the usage of the array_walk() function. Suppose we have an associative array where each element represents a person's name and age. We need to loop through this array and add an "adult" or "minor" tag based on whether the age is 18 or older. The code is as follows:

// 定义关联数组
$people = array(
    'Tom' => 25,
    'Jerry' => 17,
    'Amy' => 20,
    'John' => 10
);

// 定义回调函数,根据年龄添加标记
function calcAge($age, $name, $userData) {
  if ($age >= 18) {
    $userData[$name] = '成年人';
  } else {
    $userData[$name] = '未成年人';
  }
}

// 使用array_walk()函数遍历数组
$result = array();
array_walk($people, 'calcAge', &$result);

// 输出结果
print_r($result);

Execute the above code, we can get the following output:

Array
(
    [Tom] => 成年人
    [Jerry] => 未成年人
    [Amy] => 成年人
    [John] => 未成年人
)

As can be seen from the above code and output results, the array_walk() function can be used to easily traverse the associative array and operate on each element. In this example, we use a simple callback function to calculate the age of each element and add a marker.

In short, array_walk() is a very useful array function in PHP. It can greatly simplify the traversal and operation of arrays and reduce the coding workload. For programmers developing web applications, it is very important to master this function.

The above is the detailed content of PHP array function example: array_walk(). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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