How to Iterate Through Indexed Array Elements Using PHP

Last Updated on January 13, 2021 by Roshan Parihar

In this tutorial, learn how to iterate through indexed array elements in PHP. The short answer is: use the Foreach loop or For loop of PHP to loop over the elements.

The indexed array is the array in which elements have automatically assigned an index that starts from zero(0). It is also called a numeric array as the index is numeric for all the elements.

You can also find the matching element if present in the indexed array using the loop. However, you can use either the Foreach loop or the for loop in PHP that you can find in the example given below.

Iterate Through Indexed Array Elements Using PHP Foreach Loop

To iterate through all the elements of an indexed array, you can use the PHP foreach loop that requires argument as the indexed array variable and another variable to get the elements in the output. It parses through all the elements individually and prints each one in the output using the PHP echo statement.

Output

Cycle
Bike
Car
Bolero

The above example showing all the elements in the output and there are 4 items in the array.

Loop Over Indexed Array Elements with For Loop in PHP

In addition to the above method, you can also use the PHP For loop to traverse over all the elements of an indexed array. However, it requires to count the number of elements using the PHP count() to perform the number of iteration.

Output

Cycle
Bike
Car
Bolero

The above example showing all the elements of the array in the output. It is a little bit difficult as compared to the Foreach loop to iterate through indexed array elements in PHP.

Find the Element If Present Using Loop in PHP

Suppose, you have an element that you have to find if present in the indexed array using PHP. You can use any of the loops to perform this task. However, I recommend you to use the Foreach loop as it is faster than the For loop of PHP.

You have to first store the element in a variable that you have to match with all the elements. After that, perform the foreach loop to traverse through all the elements and use the PHP if…else condition to find the match as given below:

Output

The item ‘Car’ is present in an Indexed Array.

The above example shows that the element is present in the indexed array.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.