array_map to apply function to elements of array

This function applies any native PHP function or user defined function to each element of the array. This can be applied to multiple arrays.
array_map(my_function, array1,array2......);
my_function : Required , user defined or native PHP functions
array1 : Required , All elements has to pass through the function
array2 : Optional , All elements has to pass through the function

Output is an array ( return value of function )

Here number of arrays must be equal to number of parameters passed to array_map function.

We will try some examples.
We need to reduce the value of all the elements of an array by half. Here we can easily use array_map function and change.
$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 )

Difference between array_map and array_walk

Read more on array_walk()

Detailarray_maparray_walk
output array element Input array values remain sameInput array values updated
return value New arrayBoolean: True or False
Input Number of arrays One or moreOne only
Extra Parameter No Yes


plus2net.com




Post your comments , suggestion , error , requirements etc here .




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer