An indexed array is a simple array in which data elements are stored against numeric indexes. All the array elements are represented by an index which is a numeric value starting from 0
for the first array element.
There are two different ways of creating an indexed array in PHP, they are,
Syntax for the 1st way to create indexed array:
<?php
/*
1st - direct array initialization
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");
?>
and the syntax for the 2nd way to create indexed array is:
<?php
/*
2nd - distributed array initialization
*/
$suzuki[0] = "Swift";
$suzuki[1] = "Baleno";
$suzuki[2] = "Ertiga";
$suzuki[3] = "Brezza";
$suzuki[4] = "Vitara";
?>
No matter how we initialize the array, we can access the array as follows,
<?php
/*
Accessing array
*/
echo "Accessing the 2nd array...";
echo $suzuki[0], "\n";
echo $suzuki[3], "\n";
echo $suzuki[2], "\n";
echo "Accessing the 1st array...";
echo $lamborghinis[1], "\n";
echo $lamborghinis[0], "\n";
echo $lamborghinis[2], "\n";
?>
Accessing the 2nd array... Swift Brezza Ertiga Accessing the 1st array... Huracan Urus Aventador
Hence, to access an indexed array, we have to use the array name along with the index of the element in square brackets.
Traversing an array means to iterate it starting from the first index till the last element of the array.
We can traverse an indexed array either using a for
loop or foreach
. To know the syntax and basic usage of for
and foreach
loop, you can refer to the PHP for and foreach loop tutorial.
for
loopWhile using the for
loop to traverse an indexed array we must know the size/length of the array, which can be found using the count()
function.
Following is the syntax for traversing an array using the for
loop.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// find size of the array
$size = count($lamborghinis);
// using the for loop
for($i = 0; $i < $size; $i++)
{
echo $lamborghinis[$i], "\n";
}
?>
foreach
loopusing foreach
to traverse an indexed array is a better approach if you have to traverse the whole array, as we do not have to bother about calculating the size of the array to loop around the array.
Below we have used the foreach
to traverse the $lamborghinis
array.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
// using the foreach loop
foreach($lamborghinis as $lambo)
{
echo $lambo. "\n";
}
?>
Here are a few advantages of using indexed array in our program/script: