array_map(my_function, array1,array2......);
my_function : Required , user defined or native PHP functions $a=array(15,12,13,25,27,36,18);
function array_adj($n){
return($n/2);
}
$a=array_map("array_adj",$a);
print_r($a);
The output of above code is here
Array ( [0] => 7.5 [1] => 6 [2] => 6.5 [3] => 12.5 [4] => 13.5 [5] => 18 [6] => 9 )
Let us add elements of two arrays , note that both arrays have equal number of elements
$a=array(15,12,13,25,27,36,18);
$b=array(10,15,12,20,30,50,40);
function array_add($p,$q){
return($p+$q);
}
$c=array_map("array_add",$a,$b);
print_r($c);
The output is here
Array ( [0] => 25 [1] => 27 [2] => 25 [3] => 45 [4] => 57 [5] => 86 [6] => 58 )
We can use PHP native function also. Here is an example where we used string function strtoupper to change all lower case elements to upper case elements of an array.
$a=array('ab','cd','ef','gh');
$c=array_map("strtoupper",$a);
print_r($c);
The output is here
Array ( [0] => AB [1] => CD [2] => EF [3] => GH )
We will use one user defined function array_add to add two each elements of two arrays. We have used strings here as elements.
$a=array('ab','cd','ef','gh');
$b=array('AB','CD','EF','GH');
function array_add($p,$q){
return($p.$q);
}
$c=array_map("array_add",$a,$b);
print_r($c);
The output of above code is here.
Array ( [0] => abAB [1] => cdCD [2] => efEF [3] => ghGH )
| Detail | array_map | array_walk |
|---|---|---|
| output array element | Input array values remain same | Input array values updated |
| return value | New array | Boolean: True or False |
| Input Number of arrays | One or more | One only |
| Extra Parameter | No | Yes |
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.