array_map() function in PHP

PHPz
Release: 2023-08-27 18:14:01
forward
1558 people have browsed it

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;)
Copy after login

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);
?>
Copy after login

Output

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

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);
?>
Copy after login

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
)
)
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!