How to Access Elements in an Indexed Array Using PHP

Last Updated on January 3, 2021 by Roshan Parihar

In this tutorial, learn how to access elements in an indexed array using PHP. The short answer is: use the index operator ([]) or use the PHP foreach loop to get the elements of an indexed array.

The indexed array is the array in which the elements are stored with an automatically assign numeric index value. The index of the first element in an indexed array starts from zero (0) index value. The example of creating an indexed array in PHP is as given below:

Let’s find out how to access elements in an indexed array using PHP with the useful examples given below.

Access Elements in Indexed Array Using Index Operator [] in PHP

To get the elements of an indexed array, you have to use the index operator [] and pass the index value. The index of the first elements starts from zero (0). The below example showing the method to get the elements.

Output

Cycles
Bikes
Cars
Boleros

The above example prints all the elements of an indexed array with one element on a single line. There are 4 elements in the array.

Get Elements Using Foreach Loop in PHP

Foreach loop of PHP is the best method to traverse through each and every element of an indexed array using PHP. It parses through all the elements and prints each of them one-by-one. See the example below to learn the method.

Output

Cycles
Bikes
Cars
Boleros

The above example showing all the elements of an indexed array that gets printed using the Foreach loop. This is useful to get all the elements in one go.

Use For Loop to Access Indexed Array Data in PHP

In addition to the above all methods, you can also use the PHP for loop to traverse each and every element of an indexed array. It parses the elements one-by-one and prints them using the PHP echo function. See the example below to learn how to use the for loop method.

Output

Cycles
Bikes
Cars
Boleros

The above example parses all the elements and prints each one of them in the output.

All the methods given above are useful in PHP to access elements in an indexed array in PHP. You can use any of them to get the required output. However, the best method is through traversing that you will get with PHP Foreach and PHP for loop.

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.