![]() |
In this article, we will see array_map(), array_reduce(), and array_walk() functions in PHP. We will see how these functions work along with understanding their basic implementation through the examples. array_map() Function: The array_map() function returns an array containing the results of applying the callback to each value of the array used as arguments for the callback. In simple words, an array_map() function sends each value of an array to a user function and returns an array with new values. It’s really useful when you want to perform a specific operation on every element of an array. If you want to perform a specific action on each element of an array instead of iterating over each element of an array it is better to use an array_map() function which is built for this. An array_map() function returns an array containing the results of applying the callback function over the array. Syntax: array_map(function_name, array1, array2, array3, ...) Parameters:
Note: We can send multiple arrays in the array_map() function. Example: In this example, we calculate the square of each element in an array using the array_map() function. PHP
Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 ) array_reduce() Method: As the name suggests, an array_reduce() function reduces the array to a single value by performing the given operation. The array_reduce() applies the callback function to the elements of the array and gives output as a single value. This function was introduced in PHP 4.0.5. Syntax: array_reduce(array, myfunction, initial) Parameters:
Example: In the example, we are getting the addition of an array as a single variable. PHP
Output: 21 array_walk() Method: It applies a user-defined function to every member of an array. The array’s keys and values are parameters in the function. The array_walk() function is not affected by the internal array pointer of the array. It will traverse through all the elements. The array_map() cannot operate with the array keys, while the array_walk() function can work with the key values pair. Syntax: array_walk(array, myfunction, parameter...) Parameters:
Example: PHP
Output: Geeksforgeeks article-1 is about HTML Geeksforgeeks article-2 is about CSS Geeksforgeeks article-3 is about PHP |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |