CGPA Calculator Hash Generator Bcrypt Hasher Tree Visualizer Barcode Generator Engineering Blog Editorial Standards All Tools Games HTML5 JavaScript PHP MySQL

PHP Indexed Arrays

An indexed array is an array where each item has a numeric index. By default, the index starts at 0 and increases by one for each subsequent item.


1. Accessing Indexed Arrays

To access an element, you use square brackets with the index number of the item you want.

<?php
    $cars = ["Volvo", "BMW", "Toyota"];
    echo $cars[0]; // Outputs: Volvo
    echo $cars[1]; // Outputs: BMW
?>

2. Modifying Elements

You can change the value of an existing element by assigning a new value to its specific index.

<?php
    $cars = ["Volvo", "BMW", "Toyota"];
    $cars[1] = "Ford"; // Overwrites BMW with Ford
    
    echo $cars[1]; // Outputs: Ford
?>

3. Looping through Indexed Arrays

To print all the values of an indexed array, you can use a for loop (using the length of the array) or a foreach loop.

Using foreach (Recommended)

<?php
    $cars = ["Volvo", "BMW", "Toyota"];
    foreach ($cars as $car) {
        echo "$car <br>";
    }
?>

4. Adding New Elements

You can add a new item to the end of an indexed array using empty square brackets []. PHP will automatically assign the next available numeric index.

<?php
    $cars = ["Volvo", "BMW"];
    $cars[] = "Toyota"; // Adds to index 2
    
    print_r($cars);
?>
Technical Detail: If you try to access an index that doesn't exist (e.g., $cars[10] when there are only 3 items), PHP will return a "Warning: Undefined array key" error.
Pro Tip: Use the print_r() or var_dump() functions to quickly see the structure and contents of an array during development.

Key Points to Remember

  • Indexed arrays use numbers as keys, starting from 0.
  • Use brackets [index] to read or write specific items.
  • The foreach loop is the most efficient way to iterate through these lists.
  • Append items easily using $array[] = value.
  • Mixing data types inside an indexed array is possible but usually not recommended for clean code.