Sunday 25 August 2013

PHP Function array_map()

Syntax

array array_map ( callback $callback, array $array1 [, array $array2...] );

Definition and Usage

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().

Paramters

ParameterDescription
callbackRequired. The name of the user-made function, or null.
array1Required. Specifies an array.
array2Optional. Specifies an array.
array3Optional. Specifies an array.

Return Values

Returns an array containing all the processed elements of array1.

Example

Try out following example:
<?php
function cube($n)
{
    return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?> 
This will produce following result:
Array ( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125)
Using multiple arrays.
<?php
function call_back_func($v1, $v2)
{
   if ($v1===$v2)
   {
        return "equal";
   }
   return "different";
}

$array1 = array(1, 2, 3, 4);
$array2 = array(10, 2, 30, 4);
$b = array_map("call_back_func", $array1, $array2);
print_r($b);

?>
This will produce following result:
Array ( [0]=>different [1]=>equal [2]=>different [3]=>euqal )

No comments:

Post a Comment