PHP array_map() function

PHP array_keys() function
PHP array_merge() function

The array_map is a very useful function because it works as an iterator of arrays. It sends each element of the array to the user-defined function and returns a new array.

You can specify more than one array to the array_map function. It will work for any number of arrays.

What is the syntax of the array_map function in PHP?

array_map(myfunction, array1, array2, array3, ...)
ParametersDetails
user-defined functionName of the user-defined function. Required (can be null).
array1The array to pass its values to the user-defined function – Required
array2 Next array to pass its values to the user-defined function – Optional
array3 Next array to pass its values to the user-defined function – Optional
array_map function in PHP

Example of array_map function

<?php
function my_function($v)
{
  return($v*$v);
}

$a=array(1,2,3,4,5);
print_r(array_map("my_function",$a));
?>

Pass the array to the user-defined function that takes the square of each value and returns a new array.

<?php
function my_function($value)
{
if ($value==="Lion")
  {
  return "King";
  }
return $value;
}

$array=array("Lion","Lion","Dog");
print_r(array_map("my_function",$array));
?>

Another example is given above that modifies the values of the array.

<?php
$array_1=array("Horse","Lion");
$array_2=array("Sparrow","Parot");
print_r(array_map(null,$array_1,$array_2));
?>

In the above example, we assign null to the array_map function name parameter.

<?php
function my_function($letter)
{
$letter=strtoupper($letter);
  return $letter;
}

$array=array("Apple" => "Fruit", "Potato" => "Vegetable");
print_r(array_map("my_function",$array));
?>
PHP array_keys() function
PHP array_merge() function

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top