Master PHP’s array_map(): Basics, Advanced Tricks & Real‑World Examples
This article explains PHP’s array_map() function, covering its basic syntax, how to apply callbacks to single or multiple arrays, advanced techniques like passing extra parameters, and provides clear code examples that demonstrate transforming array data efficiently.
In PHP’s function library, the array_map() function is extremely useful for processing arrays by applying a callback to each element and returning 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 or method to be called for each element, and the $arr parameter represents the array(s) to be processed.
Example:
$arr = [1, 2, 3];
$newArr = array_map(function($v) {
return $v * 2;
}, $arr);
print_r($newArr);Running this code produces a new array where each element is multiplied by 2:
Array ( [0] => 2 [1] => 4 [2] => 6 )2. Advanced usage of array_map()
Beyond the basic usage, array_map() can handle multiple arrays and pass additional parameters to the callback.
Processing multiple arrays:
$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$newArr = array_map(function($v1, $v2) {
return $v1 + $v2;
}, $arr1, $arr2);
print_r($newArr);The result is: Array ( [0] => 5 [1] => 7 [2] => 9 ) Passing extra parameters (e.g., a prefix) to the callback:
$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);The resulting array is:
Array ( [0] => num:1 [1] => num:2 [2] => num:3 )Summary
The array_map() function is a convenient PHP tool for array manipulation; by providing different callbacks and parameters, you can perform a wide range of operations on arrays. Pay attention to the callback definition and the number of parameters passed 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.
