array_map to apply function to elements of array

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. 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(function, array1,array2......);
The function can be native php function or user defined one, array1, array2 are arrays which will be passed to the function. Here number of arrays must be equal to number of parameters passed to array_map function. We will try some examples. Let us divide all elements of an array by 2
$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 )

Subscribe to our mailing list

* indicates required
Subscribe to plus2net

Be the first to post comment on this article :


Google+

Post Comment This is for short comments only. Use the forum for more discussions.




Subscribe to our mailing list

* indicates required
Subscribe to plus2net
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us
©2000-2016 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer