Computer >> Computer tutorials >  >> Programming >> PHP

PHP Indexed Array


Definition and Usage

A comma separated sequence of values only instead of key=>value pairs. Each element in such collection has a unique positional index starting from 0. Hence, it is called Indexed array.

Indexed Array object can be initialized by array() function as well as assignment by putting elements inside square brackets [].

Syntax

//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. We can access an element from the array by its index with following syntax −

$arr[index];

PHP Version

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

Following example uses square brackets to create an indexed array

Example

<?php
$arr=[10, "ten",10.0, 1.0E1];
var_dump($arr);
?>

Output

This will produce following result −

array(4) {
   [0]=>
   int(10)
   [1]=>
   string(3) "ten"
   [2]=>
   float(10)
   [3]=>
   float(10)
}

This Example uses array() function to create indexed array

Example

<?php
$arr=array(10, "ten",10.0, 1.0E1);
var_dump($arr);
?>

Output

This will produce following result −

array(4) {
   [0]=>
   int(10)
   [1]=>
   string(3) "ten"
   [2]=>
   float(10)
   [3]=>
   float(10)
}

We can traverse the array elements using foreach loop as well as for loop as follows −

Example

<?php
$arr=array(10, "ten",10.0, 1.0E1);
//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
foreach($arr as $i){
   echo $i . " ";
}
?>

Output

This will produce following result −

10 ten 10 10
10 ten 10 10

This Example shows modify value at certain index using square brackets. To add new element, keep square brackets empty so that next available integer is used as index

Example

<?php
$arr=array(10, "ten",10.0, 1.0E1);
//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];
}
?>

Output

This will produce following result −

10 ten 10 Hello 100