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 [].
Syntax
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
Exampl-1
<?php
$size=array("Big","Medium","Short");
echo "Size: $size[0], $size[1] and $size[2]";
?>
Exampl-2
<?php
$arr=[10, "ten",10.0, 1.0E1];
var_dump($arr);
?>
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.
<?php
$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 . " ";
}
?>
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.
<?php
$arr=array("Volvo", "BMW", "Toyota", "Safari", "Bolero");
//modify existing element using index
$arr[3]="Hello";
//add new element using next index
$arr[]=100;
for ($i=0; $i< count($arr); $i++){
echo $arr[$i]." ";
}
?>
Count Length of PHP Indexed Array
PHP provides count() function which returns length of an array.
<?php
$size=array("Volvo", "BMW", "Toyota", "Safari", "Bolero");
echo count($size);
?>