Arrays are frequently used data structures in programming, and when processing arrays, changing their structures is a common requirement. In the PHP language, there are many built-in functions that can be used to accomplish this purpose, such as array_map, array_reduce, etc. This article will introduce and practical applications of these functions.
array_map function is a variable function in PHP (variable function means that you can use variables as function names in the code). This function is used to convert all the elements in an array Elements are converted by the specified callback function and a new array is returned. The number and order of elements in the new array are consistent with the original array.
Syntax: array_map(callback,array1,array2...)
Example 1:
$a = [1,2,3,4,5]; function square($n) { return $n * $n; } $b = array_map("square", $a); print_r($b);
Output result: Array ( [0] => 1 [1] => 4 [2] => 9 [3 ] => 16 [4] => 25 )
Example 2:
$a1 = [1,2,3]; $a2 = ['one', 'two', 'three']; function combine($n1, $n2) { return $n1 . $n2; } $b = array_map("combine", $a1, $a2); print_r($b);
Output result: Array ( [0] => 1one [1] => 2two [2] => 3three )
The array_reduce function is used to iterate all elements in the array one by one by specifying a callback function and return a single value.
Syntax: array_reduce (array, callback, [initial_value])
Example one:
$a = [1, 2, 3, 4, 5]; $sum = array_reduce($a, function($total, $num){ return $total + $num; }); echo $sum;
Output result: 15
Example two:
$a = ['Hello', 'World', '!']; $sentence = array_reduce($a, function($sentence, $word){ return $sentence . ' ' . $word; }); echo $sentence;
Output result: Hello World!
array_map and array_reduce functions are very practical array traversal functions. They can help us quickly change the structure of the array to meet our needs. Everyone can apply it flexibly in development and make practical applications based on their own needs.
The above is the detailed content of Quick methods to change the array structure: array_map, array_reduce, etc.. For more information, please follow other related articles on the PHP Chinese website!