What are array_map(), array_reduce() and array_walk() function in PHP ?
Last Updated :
25 Mar, 2022
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:
- function_name: A callable function to apply to each element in each array.
- array1: It is an array of elements to which the callback function applies.
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
<?php
function square($n) {
return ($n * $n);
}
$a = [1, 2, 3, 4, 5];
$b = array_map('square', $a);
print_r($b);
?>
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:
- array: It is the input array that will be reduced to a single value.
- myfunction: It is a callback function that determines how the array should be reduced.
- initial: It is an optional value that will be used at the beginning of the process, or as a final result in case the array is empty.
Example: In the example, we are getting the addition of an array as a single variable.
PHP
<?php
function add($num1, $num2) {
$num1 += $num2;
return $num1;
}
$a = array(1, 2, 3, 4, 5, 6);
$num1 = array_reduce($a, "add");
echo $num1;
?>
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:
- array: The input array.
- myfunction: Name of the function
- parameter: Specifies a parameter to the user-defined function. You can assign multiple parameters.
Example:
PHP
<?php
function myfunction($value,$key) {
echo "Geeksforgeeks $key is about $value \n";
}
$articles = array(
"article-1" => "HTML",
"article-2" => "CSS",
"article-3" => "PHP"
);
array_walk($articles,"myfunction");
?>
Output:
Geeksforgeeks article-1 is about HTML
Geeksforgeeks article-2 is about CSS
Geeksforgeeks article-3 is about PHP
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. Example of an AVL Tree:The balance factors for different nodes are : 12 :1, 8:1, 18:1, 5:1, 11:0, 17:0 and 4:0. Since all differences
4 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read