Home > Article > Backend Development > Introduction and example usage of PHP’s array_walk() function
In PHP, there are many practical functions that can help us process arrays more conveniently. Among them, the array_walk() function is a very practical function. It can perform specified operations on each element in the array. Let us take a look.
array_walk() function is a function used to process arrays. Its syntax structure is as follows:
array_walk( array &$array, callable $callback [, mixed $userdata = NULL]): bool
Parameter description:
Now, let’s look at some examples of the array_walk() function to help you better understand its use.
Example 1: Convert each element in the array to uppercase
First, we create an array and convert the letters in it to lowercase:
$array = array("name" => "jane", "age" => 25, "job" => "developer");
Then, use the array_walk() function combined with the callback function to convert all characters to uppercase:
array_walk($array, function(&$value){ if(is_string($value)){ $value = strtoupper($value); } });
In the above callback function, the strtoupper() function is used to convert the characters to uppercase. $value represents each element in the array. At the same time, we use the & symbol in the function to indicate that the variable passed is a reference type. In this way, modifying the value of $value within the function will also affect the original array.
Example 2: Multiply all numeric elements in the array by 2
Next, let’s look at a more practical example, where we multiply all numeric elements in the array by 2. We also create an array:
$array = array("name" => "jane", "age" => 25, "job" => "developer", "salary" => 5000);
Then use the array_walk() function combined with the callback function to multiply all numeric elements by 2:
array_walk($array, function(&$value){ if(is_numeric($value)){ $value = $value * 2; } });
In the above callback function, is_numeric is used The () function determines whether $value is a number. If it is a number, it is multiplied by 2, otherwise no processing is performed. In this way, we have completed processing of digital elements.
The array_walk() function is a very practical function and is widely used in PHP array processing. Using this function allows us to better handle arrays and simplify code implementation. I hope this article can help everyone better understand and apply this function.
The above is the detailed content of Introduction and example usage of PHP’s array_walk() function. For more information, please follow other related articles on the PHP Chinese website!