In this article, we will elaborate on the “each()” function in PHP along with its syntax, limitations, and alternate methods for array iteration.
What is the “each()” function in PHP?
In PHP, the “each()” function is mostly used to access pairs of the key value once at a time by iterating across arrays. It returns an array with four elements, such as the key and value of the present element, a boolean showing if the iteration of elements has ended, and the key-value pair for the subsequent element.
Note: Use this compiler to test the following example code.
Syntax
The syntax of the above-discussed function is as follows:
Parameter: It accepts an array as an argument.
Return Value: It returns the string key-value pair that currently exists in an index array, where the key is the first element and the value is the second. Otherwise, it produces “false” values if the array is empty and its pointer reaches the end of an array.
Here’s a structural representation of each element:
Examples: Use each() Function to Print Indexed Array
To print the indexed array by using the “each()” function, first, initialize the “$Shape” array with three elements “Circle”, “Rectangle”, and “Square” respectively. Then, call the “each()” function inside the “print_r()” function and pass the array “$Shape” as an argument to get the “key/value” pair of an array:
The output of the above-stated code is shown below:
Example 2: Use each() Function with While Loop
Take another example to use the “each()” function with a while loop in PHP. To do so, first, initialize the “$colors” variable which has “Red,” “Blue,” and “White” keys with the “#FF0000” for red, “#00FF00” for green, and “#0000FF” for blue values of an associative array.
After this, use the “while” loop to iterate each element of the “$colors” array. Next, apply the “echo” statement to print the output of the color key “$color[‘key’]”, with respect to their corresponding color code “$color[‘value’]”:
Output
Limitations of each() Function in PHP
- Although the “each()” function can be useful, it has certain limitations. It operates on the internal array pointer and modifies the array, making it less suitable for nested iterations or when users need to preserve the state of the original array in PHP.
Similar Methods to Overcome Limitations
- Alternate solutions that PHP gives to get past these limits include “foreach” loops, which offer a cleaner and more intelligible syntax, or using the array_keys(), or array_walk() functions, depending on the unique requirements of your code.
We described the detailed information about the “each()” function in PHP.
Conclusion
In PHP, the “each()” function is widely used in earlier versions to traverse arrays, retrieve key-value pairs, and advance the internal array pointer. In this guide, we explained the “each()” function with the aid of different examples and provided its limitations as well as similar methods.