Home >Backend Development >PHP Tutorial >How to use array_map() function in php? (code example)
The array_map() function is a built-in function in PHP, which can modify all elements in one or more arrays based on user-defined conditions (functions) in a simple way. Let's introduce in detail how to use the array_map() function.
##array_map() function
array_map() function basically converts each element of the array Send it to a user-defined function for modification or processing, and then return an array with the new value modified by the function.Basic syntax:
array_map(functionName,arr1,arr2...)
Description:
functionName parameter: required, representing the name of the user-defined function. The array_map() function will pass the value of the array to the function for processing based on the name, and then return. arr1, arr2... Parameters: required items, representing the array that needs to be modified, which can be one array or multiple arrays. The functionName parameter is mandatory, we can pass any number of arrays (arr1, arr2...., and so on) to the function for processing.Usage example of array_map() function
Let’s introduce the use of array_map() function through a simple exampleExample 1: Processing values in the array
<?php function fun1($v) { return ($v + 7); // 数组中的每个元素值都加7 } function fun2($v1,$v2) { //判断两个数组中对应的值是否相等,相等则返回1,不相等则返回0。最后形成一个由1和0组成的数组 if ($v1 == $v2) return 1; else return 0; } $arr1 = array(1, 2, 3, 4, 5); $arr2 = array(1, 3, 3, 4, 8); echo "<pre class="brush:php;toolbar:false">"; print_r(array_map("fun1", $arr1)); print_r(array_map("fun2", $arr1, $arr2)); echo ""; ?>Output:
<?php $a = array(1, 2, 3); $b = array("one", "two", "three"); $result = array_map(null, $a, $b); echo "<pre class="brush:php;toolbar:false">"; print_r($result); echo ""; ?>In PHP, use the array_map() function to create nested arrays. For this we have to pass null as parameter instead of functionName parameter and array list to create array of arrays. Output: The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant column tutorials on the PHP Chinese website! ! !
The above is the detailed content of How to use array_map() function in php? (code example). For more information, please follow other related articles on the PHP Chinese website!