Home >>PHP Array Functions >PHP array_map() Function

PHP array_map() Function

PHP array_map() Function

PHP array_map() function is used to modify all the elements of one or more given input arrays according to some user-defined condition in an easy way. It sends each of the elements of the array to a user-defined function and returns an array with new values modified by that function. It accepts two mandatory and other optional parameters.

Syntax:

array_map(function, $array1, $array2, $array3, ...);

Parameter Values

Parameter Description
function This is a required parameter. This parameter defines the name of the user-made function.
array1 This is a required parameter. This parameter defines an array.
array2 This is an optional parameter. This parameter defines an array.
array3 This is an optional parameter. This parameter defines more arrays.

Here is an example of array_map() function in PHP:

<html>
<body>
<pre>
<?php
function square($num)
{
  return($num*$num);
}
$a=array(0,1,2,3,4,5);
print_r(array_map("square",$a));
?>
</pre>
</body>
</html>
Output:
Array
(
    [0] => 0
    [1] => 1
    [2] => 4
    [3] => 9
    [4] => 16
    [5] => 25
)

Example 2:

<html>
<body>
<pre>
<?php
function Multiply($num)
{
  return($num*13);
}
for($i=1;$i<=10;$i++)
{
$a[]=$i;
}
print_r(array_map("Multiply",$a));
?>
</pre>
</body>
</html>
Output:
Array
(
    [0] => 13
    [1] => 26
    [2] => 39
    [3] => 52
    [4] => 65
    [5] => 78
    [6] => 91
    [7] => 104
    [8] => 117
    [9] => 130
)

No Sidebar ads