Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

Indexed Arrays

In indexed arrays, each item has an index number.

By default, the first item has an index of 0, the second item has an index of 1, and so on.

Example

Create and output an indexed array:

$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);

Access Indexed Arrays

To access an array item, you can use its index number.

Example

Output the first item of the array:

$cars = array("Volvo", "BMW", "Toyota");
echo $cars[0];

Change Value

To modify the value of an array item, use its index number:

Example

Update the value of the second item:

$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
var_dump($cars)

Loop Through an Indexed Array

To iterate through and display all the values of an indexed array, you can use a foreach loop, as follows:

Example

Output all items in the array:

$cars = array("Volvo", "BMW", "Toyota")
foreach ($cars as $x) {
 echo "$x <br>";
}

Index Number

The key of an indexed array is a number, with the first item being 0, the second 1, and so on, although there are exceptions.

New items receive the next index number, which is one greater than the highest existing index.

For example, if you have an array like this:

$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

If you use the array_push() function to add a new item, the new item will be assigned the index 3.

Example

array_push($cars, "Ford");
var_dump($cars);

However, if you have an array with random index numbers, like this:

$cars[5] = "Volvo";
$cars[7] = "BMW";
$cars[14] = "Toyota";

If you use the array_push() function to add a new item, what will be its index number?

Example

array_push($cars, "Ford");
var_dump($cars);