Skip to content

PHP Create Indexed Arrays

Syntax

Indexed arrays in PHP are created with numeric keys starting from 0 by default. They can be created using the array() function or the shorthand [] syntax.

$arrayName = [element1, element2, element3]; // Using square brackets
$arrayName = array(element1, element2, element3); // Using array() function
// Using array() to create an indexed array
$numbers = array(10, 20, 30);
// Using shorthand [] syntax
$fruits = ["Apple", "Banana", "Cherry"];
// Adding elements to an indexed array
$fruits[] = "Dragonfruit";
// Accessing elements by index
echo $fruits[0]; // Outputs: Apple

Example

<?php
// Creating an indexed array
$colors = ["Red", "Green", "Blue"];
// Accessing elements
echo "First color: " . $colors[0] . "\n"; // Outputs: First color: Red
// Modifying an element
$colors[1] = "Yellow";
echo "Updated second color: " . $colors[1] . "\n"; // Outputs: Updated second color: Yellow
// Adding elements
$colors[] = "Purple";
echo "Added color: " . $colors[3] . "\n"; // Outputs: Added color: Purple
?>