PHP Indexed Arrays
markdown
Arrays are one of the most important data structures in PHP. They allow developers to store multiple values in a single variable. Among the different types of arrays in PHP, Indexed Arrays are the simplest and most commonly used.
This guide explains what indexed arrays are, how they work, how to create and access elements, and includes clear developer-friendly examples for your PHP learning series.
A PHP indexed array is an array where each element is assigned an index number automatically. The index always starts from 0 unless manually changed.
Example:
$colors = ["Red", "Green", "Blue"]; // Indexed automatically as 0,1,2
Indexed arrays are useful when you need to store a list of items such as:
Names
Colors
Numbers
City list
Product items
There are two main ways to create indexed arrays.
$fruits = ["Apple", "Banana", "Mango"];
array() Function
$fruits = array("Apple", "Banana", "Mango");
Both methods work exactly the same.
You can access elements using their index number.
$fruits = ["Apple", "Banana", "Mango"];
echo $fruits[0]; // Apple
echo $fruits[2]; // Mango
If you try to access an index that doesn’t exist, PHP will throw a notice.
You can add values simply by using [] without specifying an index.
$numbers = [10, 20, 30];
$numbers[] = 40; // Adds 40 at index 3
$numbers[] = 50; // Adds 50 at index 4
You can change a value by accessing its index.
$fruits = ["Apple", "Banana", "Mango"];
$fruits[1] = "Orange"; // Banana becomes Orange
for Loop
$colors = ["Red", "Green", "Blue"];
for ($i = 0; $i < count($colors); $i++) {
echo $colors[$i] . "<br>";
}
foreach Loop (Recommended)
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo $color . "<br>";
}
$students = ["Amit", "Rahul", "Sneha", "Priya"];
echo "List of Students:<br>";
foreach ($students as $name) {
echo $name . "<br>";
}
count() – Returns number of elements
$count = count($students);
array_push() – Adds elements
array_push($students, "Rohan", "Vikas");
array_pop() – Removes last element
array_pop($students);
sort() – Sorts array in ascending order
sort($students);
implode() – Convert array to string
echo implode(", ", $students);
Easy to understand
Simple syntax
Fast access using index
Ideal for lists and collections
Indexed arrays are one of the simplest yet most useful features in PHP. Whether you're storing names, numbers, or a list of items, indexed arrays make it easy to organize and retrieve data quickly. They are essential for beginners and developers working with any kind of list-based data.
Learn what PHP indexed arrays are, how to create them, access elements, loop values, and use built-in functions. Beginner-friendly tutorial with examples.
php indexed arrays, php arrays tutorial, php array example, php beginner tutorial, php array functions
"PHP indexed arrays tutorial with beginner-friendly examples"