Master PHP’s array_map(): Transform Arrays with Simple Callbacks
This article explains the PHP array_map() function, covering its basic syntax, simple examples, and advanced techniques such as handling multiple arrays and passing extra parameters to callbacks, enabling developers to efficiently transform and manipulate array data.
In PHP's function library, the array_map() function is a powerful tool that applies a callback to each element of an array and returns a new array.
1. Basic usage of array_map()
The basic syntax is: array_map(callable $callback, array ...$arr) The $callback parameter is the function to be called for each element, and $arr represents the array(s) to process. Multiple arrays can be passed.
Example:
$arr = [1, 2, 3];
$newArr = array_map(function($v) {
return $v * 2;
}, $arr);
print_r($newArr);Output:
Array ( [0] => 2 [1] => 4 [2] => 6 )2. Advanced usage of array_map()
array_map()can handle multiple arrays and pass additional parameters to the callback.
Example with two arrays:
$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$newArr = array_map(function($v1, $v2) {
return $v1 + $v2;
}, $arr1, $arr2);
print_r($newArr);Result: Array ( [0] => 5 [1] => 7 [2] => 9 ) Example passing extra parameter:
$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);Result:
Array ( [0] => num:1 [1] => num:2 [2] => num:3 )Conclusion
The array_map() function simplifies array processing in PHP. By providing appropriate callbacks and parameters, you can perform a wide range of transformations. Pay attention to the number of arguments and callback logic to achieve the desired results.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
