PHP Indexed Array

PHP indexed array is useful to create a simple array to store data. The data is arranged in an indexed order that starts from zero (0).

What is PHP Indexed Array?

It is an array in which items are placed in a variable with a numeric index value. Each element has an automatically assigned index value that starts from zero (0).

The meaning of indexed is that the elements are recorded with index. You can also assign index values manually to the elements. However, the index values should be numeric.

How to Create Indexed Array in PHP (2 Ways with Examples)

To create the array in PHP, you have to choose your preferred way to use and create the array in PHP from two of them:

First Method: Automatically Assigned Indexed Values.

Output

Cycle
Bike
Car
Bolero

Second Method: Manually Assigned Indexed Values.

Output

Cycle
Bike
Car
Bolero

Traverse Through Each Element to Access Them

Traversing through elements of an indexed array is the process to loop through all the elements to access them individually. You can use either PHP Foreach loop or PHP for loop to loop through all the elements one-by-one.

See the examples to learn the method of traversing.

Using PHP Foreach Loop

Output

Cycle
Bike
Car
Bolero

Using PHP For Loop

Output

Cycle
Bike
Car
Bolero

Out of the above two methods, the PHP foreach loop is the fastest and the recommended method to traverse through all the elements of an array.

Find Length or Size in PHP

You can count the number of elements present in an indexed array. To find the size of an indexed array, you have to use the PHP sizeof() function as given below:

Output

4

The above example shows that there are 4 elements present in an indexed array.

You May Also Like to Read