PHP array map example

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 5.5.9 (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);
?>
Env: PHP 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments