PHP Indexed Arrays
In this page:
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
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0];
?>
Login to try C/C++/Java/PHP code in the editor
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
$colors = ["red", "green", "yellow"];
$colors[2] = 'blue';
print_r($colors);
?>
Login to try C/C++/Java/PHP code in the editor
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
$fruits = ["apple", "banana"];
$fruits[] = 'mango';
print_r($fruits);
?>
Login to try C/C++/Java/PHP code in the editor
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
$fruits = ["apple", "banana", "mango"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
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
$tasks = ["Write report", "Send email", "Attend meeting"];
foreach ($tasks as $index => $task) {
echo ($index + 1) . ". " . $task . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: