We use indexed arrays to store lists of items in order. Each item has a number called an index, starting from zero.
Indexed array creation in PHP
<?php // Create an indexed array $array = array('value1', 'value2', 'value3'); // Or using short syntax $array = ['value1', 'value2', 'value3']; ?>
Indexed arrays start with index 0 for the first item.
You can use either the array() function or the short [] syntax to create arrays.
<?php // Empty indexed array $emptyArray = array(); ?>
<?php // Array with one item $singleItemArray = ["apple"]; ?>
<?php // Array with multiple items $fruits = ["apple", "banana", "cherry"]; ?>
<?php // Mixing types in an indexed array $mixedArray = [10, "hello", 3.14]; ?>
This program creates an indexed array of colors, prints it, adds a new color, then prints the updated array.
<?php // Create an indexed array of colors $colors = ["red", "green", "blue"]; // Print the array before adding a new color print_r($colors); // Add a new color at the end $colors[] = "yellow"; // Print the array after adding print_r($colors); ?>
Creating an indexed array is very fast, with time complexity O(1) for adding items at the end.
Indexed arrays use memory proportional to the number of items stored.
A common mistake is to confuse indexed arrays with associative arrays, which use named keys instead of numbers.
Use indexed arrays when order matters and you want to access items by their position number.
Indexed arrays store items in order, starting at index 0.
You can create them using array() or [] syntax.
They are useful for lists where position matters.