Using PHP’s array_map() Function: Basic and Advanced Usage
This article explains PHP’s array_map() function, covering its basic syntax, how callbacks and array arguments work, and demonstrates simple and advanced examples—including processing multiple arrays and passing extra parameters—to show how to transform arrays efficiently.
The array_map() function in PHP is a powerful utility that applies a callback to each element of one or more arrays and returns a new array with the transformed values.
1. Basic Usage of array_map()
The basic syntax of array_map() is:
<code>array_map(callable $callback, array ...$arr)</code>The $callback parameter is the function or method that will be called for each element, and $arr represents the array(s) to be processed.
Example:
<code>$arr = [1, 2, 3];
$newArr = array_map(function($v) {
return $v * 2;
}, $arr);
print_r($newArr);
</code>Running this code outputs Array ( [0] => 2 [1] => 4 [2] => 6 ) , a new array where each original element has been multiplied by 2.
2. Advanced Usage of array_map()
Beyond the basic case, array_map() can handle multiple arrays and pass additional parameters to the callback.
Processing multiple arrays:
<code>$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$newArr = array_map(function($v1, $v2) {
return $v1 + $v2;
}, $arr1, $arr2);
print_r($newArr);
</code>This produces Array ( [0] => 5 [1] => 7 [2] => 9 ) , the element‑wise sum of the two arrays.
You can also pass extra arguments after the array parameters. Example:
<code>$arr = [1, 2, 3];
$prefix = 'num:';
$newArr = array_map(function($v, $prefix) {
return $prefix . $v;
}, $arr, array_fill(0, count($arr), $prefix));
print_r($newArr);
</code>The result is Array ( [0] => num:1 [1] => num:2 [2] => num:3 ) , where each element is prefixed with "num:".
Conclusion
The array_map() function is a convenient way to manipulate arrays in PHP; by providing different callbacks and parameters, you can perform a wide range of transformations. Pay attention to the number of arguments your callback expects to obtain the desired results.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.