PHP Indexed Array

PHP Indexed Array is simple array with a numeric key. PHP indexed array is also known as numeric array.

Indexed Arrays are arrays in which the elements are ordered based on index. All the array elements are represented by an index which is a numeric value starting from 0 for the first array element.

The index can be used to access or modify the elements of array.

An array can be created using the array() language construct or by putting elements inside square brackets [].


There are two different ways of creating an indexed array in PHP as shown below.

//Indexed array using array() function
$arr=array(val1, val2,val3,..);
//Indexed array using assignment method
$arr=[val1, val2, val3,..];

An element in the array can be of any PHP type.

To access an indexed array, we have to use the array name along with the index of the element in square brackets.

PHP Indexed Array Example


echo "Size: $size[0], $size[1] and $size[2]";  
PHP Indexed Array Example – 1 Output


$arr=[10, "ten",10.0, 1.0E1];
PHP Indexed Array Example – 2 Output

Use of square brackets for assignment of array is available since PHP 5.4

Traversing PHP Indexed Array

Traversing an array means to iterate it starting from the first index till the last element of the array.

We can traverse the array elements using foreach loop as well as for loop as shown in below example.

$arr=array("Volvo", "BMW", "Toyota", "Safari", "Bolero");
//using for loop. Use count() function to determine array size.
for ($i=0;$i < count($arr); $i++){
   echo $arr[$i] . " ";
echo "\n";
//using foreach loop
echo "<br>//using foreach loop<br>";
foreach($arr as $i){
   echo $i . " ";
Traversing PHP Indexed Array Example – Output

Modifying value at certain index.

Below example shows modifying value at certain index using square brackets.

To add new element, keep square brackets empty so that next available integer is used as index.

$arr=array("Volvo", "BMW", "Toyota", "Safari", "Bolero");
//modify existing element using index
//add new element using next index
for ($i=0; $i< count($arr); $i++){
   echo $arr[$i]." ";
Modifying value at certain index example – output

Count Length of PHP Indexed Array

PHP provides count() function which returns length of an array.

$size=array("Volvo", "BMW", "Toyota", "Safari", "Bolero");  
echo count($size);  
Count Length of PHP Indexed Array Example – Output