Home >Backend Development >PHP Tutorial >array_map() function in PHP

array_map() function in PHP

PHPz
PHPzforward
2023-08-27 18:13:051607browse

array_map() function in PHP

array_map() function sends each value of the array to a user-written function, which returns the new value.

Syntax

array_map(callback, arr1, <strong>arr2 &minus;</strong>, <strong>arr3 &minus;</strong>, <strong>arr4 &minus;</strong>, &hellip;)

Parameters

  • callback−Callback function

  • arr1 - Array to be modified

  • arr2 - Array to be modified

  • arr3 - The array to modify

Returns

array_map() function returns an array containing the user-created function after applying it to each array. The value of the first array.

Example

Real-time demonstration

<?php
function square($n) {
   return($n * $n);
}
$arr = array(1, 2, 3);
$res = array_map("square", $arr);
print_r($res);
?>

Output

Array
(
[0] => 1
[1] => 4
[2] => 9
)

Example

Let us look at another example of using array_map() to create an array of arrays Example.

Real-time demonstration

<?php
$arr1 = array(1, 2, 3);
$arr2 = array("steve", "david", "nadal");
$arr3 = array("cricket", "football", "tennis");
$res = array_map(null, $arr1, $arr2, $arr3);
print_r($res);
?>

Output

Array
(
[0] => Array
(
[0] => 1
[1] => steve
[2] => cricket
)

[1] => Array
(
[0] => 2
[1] => david
[2] => football
)

[2] => Array
(
[0] => 3
[1] => nadal
[2] => tennis
)
)

The above is the detailed content of array_map() function in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete