1. php
  2. /references
  3. /indexed-array

PHP Indexed Arrays

An indexed array in PHP is an array that uses numbers as its keys. An array can be created by enclosing a comma-separated list of values in square brackets [], or by using the array function.

Usage

Here's an example of creating an array using both methods:

// Bracketed array
$fruits = ['apple', 'banana', 'orange'];

// Using the array function
$fruits = array('apple', 'banana', 'orange');

Looping through an indexed array

To loop through an indexed array, you can use a for loop. Here's an example of how to loop through the $fruits array and print out each value:

for ($i = 0; $i < count($fruits); $i++) {
    echo $fruits[$i] . "\n";
}

Alternatively, you can use a foreach loop, which is more concise and easier to read. Here's how to do it:

foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}

This will output:

apple
banana
orange

See also:

PHP Associative Array

PHP Multidimensional Array