PHP

PHP array_map

An array_map is a function in PHP. Which is used to get a new array automatically by multiplying the existing array values by themselves. If we say we have an array and we want each value got to multiply by itself and we got a new array in return so for such tasks we use the array map function in PHP.  The map function doesn’t do any change in the existing array beside it does calculations on each value of the existing array and in return, it gives the new array. Let’s take an example:

PHP array_map function

Example

<?php

function myfunction($no)
{

  return($no*$no);

}

$a=array(6,7,8,9,10);

print_r(array_map("myfunction",$a));

?>

Output

In other words, each value of array $a will go to the myfunction and then it will multiply by itself and the new array value will be printed through the array_Map() function.

PHP array_map function using two arrays

Example

<?php

function square($n,$m)
{
  return("$n=$m");
}

$a=array(6,7,8,9,10);

$b=array('apple','banana','orange','mango','grapes');

$newArray=(array_map("square",$a,$b));

echo "<pre>";

  print_r($newArray);

"</pre>";

?>

In the above example we declared two arrays $a and $b then we create a new array in which we stored the result of the array_map() function. And we give it three parameters first one is the function name and second is 1st array variable and the other one is 2nd array variable. then we create a function named a square in which we declare two parameters $n and $m. $n will contain the value of $a and the $m will contain the value of $b and then we return the new Associative array value as you can see in the output below:

Output

As you can see both array values are showing simultaneously in a single array we did not need to send each value of the array to the function the advantage of using the PHP array_map() function is we get a new Associative array that created automatically.

Multidimensional array using array_Map() function

Example


<?php

function square($n,$m)
{
  Return [$n=>$m];
}

$a=array(6,7,8,9,10);

$b=array('apple','banana','orange','mango','grapes');

$newArray=(array_map("square",$a,$b));

echo "<pre>";

  print_r($newArray);

"</pre>";

?>


We took the same example and we just add a few changes, for making it the multidimensional associative array. We remove the double quotation in the return statement, and in place of  = we use the arrow operator => and then closed the bracket. now we will get Mulitidimentional Associative Array. see the output below:

Output

Conclusion

In today’s tutorial, we discuss what is array_map() Function in PHP, we discuss its examples and try it applying different operations then we see how to make an associative array by 2 arrays using the array_map() Function, and then we see another example of Multidimensional Array.

Suggested Articles:

Leave a Comment