PHP array map applies the callback function to one or more arrays. In callback we can use a function or anonymous function. Here are some examples.
array_map with one array
Here we’ll use anonymous function which adds 1.
<?php $a = array(10, 20, 30, 40); $new = array_map(function($v) {return $v+1;}, $a); print_r($new); ?>
Array ( [0] => 11 [1] => 21 [2] => 31 [3] => 41 )
Env: PHP 7.4.33 (Linux)
array_map with multiple arrays
Here we’ll use function which add two arguments. Also note that in case arrays have different lengths, null
is passed for missing values.
<?php $a = array(10, 20, 30, 40); $b = array(1, 2, 3); function mysum($v1, $v2) { return $v1+$v2; } $new = array_map("mysum", $a, $b); print_r($new); ?>
Array ( [0] => 11 [1] => 22 [2] => 33 [3] => 40 )
Env: PHP 7.4.33 (Linux)