Wednesday, 24 September 2014

array_map in PHP

PHP array_map() function sends every value of an array to a user-made function, and gives back an array with new values, given by the user-defined function

Syntax for PHP array_map()

array_map(function,array1,array2,array3...)
function : Required. Name of the user-made function, or null
array1 : Required. Specifies an array
array2 : Optional. Specifies an array
array3 : Optional. Specifies an array
Tip : You can assign one array to the function, or as many as you like.

Example on PHP array_map()

<?php
function myfunc($par1,$par2)
{
if($par1===$par2)
{
return "same";
}
return "different";
}
$daysarr1 = array("Sunday","Monday","Tuesday");
$daysarr2 = array("Wednesday","Friday","Tuesday");
print_r(array_map("myfunc",$daysarr1,$daysarr2));
$daysarr1 = array("Sunday","Monday");
$daysarr2 = array("Tuesday","Wednesday");
echo "<br />"."assigning function name as null";
print_r(array_map(null,$daysarr1,$daysarr2));
?>

Output will be:

Array (
           [0] => different
           [1] => different
           [2] => same
         ) 
assigning function name as null
Array (
          [0] => Array (
                               [0] => Sunday
                               [1] => Tuesday
                             )
          [1] => Array (
                               [0] => Monday
                               [1] => Wednesday
                             )
          )
 
 
Brief Explanation about array_map():
 
array_map():Applies the callback to the elements of the given arrays 
Syntax:array array_map( callable $callback, array $array1[, array $...])
 
array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()


Parameters: 

callback

Callback function to run for each element in each array.
array1
An array to run through the callback function.
...
Variable list of array arguments to run through the callback function.

Return Values

Returns an array containing all the elements of array1 after applying the callback function to each one.
 
 Example:
<?phpfunction cube($n)
{
    return(
$n $n $n);
}
$a = array(12345);$b array_map("cube"$a);print_r($b);?>

Output:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)
 
Example2:
<?php
$func 
= function($value) {
    return 
$value 2;
};
print_r(array_map($funcrange(15)));?>
Output: 

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)
 
 

0 comments:

Post a Comment