Home >Backend Development >PHP Tutorial >Several methods of traversing arrays in PHP_PHP tutorial
There are three commonly used methods to traverse arrays in PHP:
1. Use the for statement to loop through the array;
2. Use the foreach statement to traverse the array;
3. Use list(), each() and while loop in combination Traverse the array.
The most efficient of these three methods is to use the foreach statement to traverse the array. The foreach structure has been introduced since PHP4. It is a statement specifically designed for traversing arrays in PHP and is recommended for everyone to use. Let’s first introduce these methods respectively.
1. Use the for statement to loop through an array
It is worth noting that using the for statement to loop through an array requires that the array traversed must be an index array. There are not only associative arrays but also index arrays in PHP, so the for statement is rarely used in PHP to loop through arrays.
The example code is as follows: