Home >Backend Development >PHP Tutorial >array_map() function in PHP
array_map() function sends each value of the array to a user-written function, which returns the new value.
array_map(callback, arr1, <strong>arr2 −</strong>, <strong>arr3 −</strong>, <strong>arr4 −</strong>, …)
callback−Callback function
arr1 - Array to be modified
arr2 - Array to be modified
arr3 - The array to modify
array_map() function returns an array containing the user-created function after applying it to each array. The value of the first array.
Real-time demonstration
<?php function square($n) { return($n * $n); } $arr = array(1, 2, 3); $res = array_map("square", $arr); print_r($res); ?>
Array ( [0] => 1 [1] => 4 [2] => 9 )
Let us look at another example of using array_map() to create an array of arrays Example.
Real-time demonstration
<?php $arr1 = array(1, 2, 3); $arr2 = array("steve", "david", "nadal"); $arr3 = array("cricket", "football", "tennis"); $res = array_map(null, $arr1, $arr2, $arr3); print_r($res); ?>
Array ( [0] => Array ( [0] => 1 [1] => steve [2] => cricket ) [1] => Array ( [0] => 2 [1] => david [2] => football ) [2] => Array ( [0] => 3 [1] => nadal [2] => tennis ) )
The above is the detailed content of array_map() function in PHP. For more information, please follow other related articles on the PHP Chinese website!