← Back to PHP Course | Chapter 7: Arrays | Lesson 7 of 13

PHP Indexed Arrays

Creating Indexed Arrays

An indexed array uses automatically assigned, sequential integer keys starting at 0, so $fruits[0] refers to the first element you added, exactly like arrays in most other programming languages.

Example: Creating Indexed Arrays

php
<?php
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0];
?>

Accessing Array Elements

You can access or overwrite any element by its numeric position, such as $colors[2] = blue;, and PHP will happily let you skip indices, creating gaps that count() still accounts for correctly.

Example: Accessing Array Elements

php
<?php
$colors = ["red", "green", "yellow"];
$colors[2] = 'blue';
print_r($colors);
?>

Adding Elements to Arrays

$fruits[] = mango; appends a new value to the end of an indexed array, automatically assigning it the next available integer key without you needing to track the current highest index yourself.

Example: Adding Elements to Arrays

php
<?php
$fruits = ["apple", "banana"];
$fruits[] = 'mango';
print_r($fruits);
?>

Removing Array Elements

foreach ($array as $value) is the idiomatic way to loop over an indexed array's values in order, and is generally preferred over a manual for loop with a counter since it can't accidentally run past the array's bounds.

Example: Removing Array Elements

php
<?php
$fruits = ["apple", "banana", "mango"];
foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}
?>

Modifying and Reindexing

Indexed arrays are the natural fit for ordered lists like a queue of tasks or a sequence of steps, where the position of an item (first, second, third) carries meaning rather than a descriptive label.

Example: Modifying and Reindexing

php
<?php
$tasks = ["Write report", "Send email", "Attend meeting"];
foreach ($tasks as $index => $task) {
    echo ($index + 1) . ". " . $task . "\n";
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.