0
0
PhpConceptBeginner · 3 min read

What is Indexed Array in PHP: Simple Explanation and Example

An indexed array in PHP is a type of array where each element is automatically assigned a numeric key starting from 0. It works like a list where you access items by their position number. This is different from associative arrays that use named keys.
⚙️

How It Works

Think of an indexed array like a row of mailboxes numbered from 0 upwards. Each mailbox holds a value, and you can find any value by knowing its mailbox number. In PHP, when you create an indexed array, PHP automatically assigns these numbers as keys starting at 0.

This means you don't have to name each key yourself; PHP does it for you. You just put values in order, and PHP keeps track of their positions. When you want to get a value, you ask for the number (index) of the mailbox.

💻

Example

This example shows how to create an indexed array and access its elements by their numeric keys.

php
<?php
$fruits = ["Apple", "Banana", "Cherry"];

// Access elements by index
echo $fruits[0] . "\n"; // Apple
echo $fruits[1] . "\n"; // Banana
echo $fruits[2] . "\n"; // Cherry
?>
Output
Apple Banana Cherry
🎯

When to Use

Use indexed arrays when you have a list of items where order matters and you want to access items by their position. For example, storing a list of names, numbers, or any sequence of values.

They are great for simple collections like days of the week, shopping lists, or any time you want to loop through items in order.

Key Points

  • Indexed arrays use numeric keys starting at 0 by default.
  • They are like ordered lists where position matters.
  • You access elements by their index number.
  • PHP assigns keys automatically unless you specify them.

Key Takeaways

An indexed array in PHP stores values with numeric keys starting at 0.
You access elements by their position number in the array.
Use indexed arrays for ordered lists where the sequence matters.
PHP automatically assigns numeric keys unless you specify otherwise.