PHP Fundamentals

Indexed Arrays

13 min Lesson 11 of 45

Understanding Indexed Arrays

Arrays are one of the most important data structures in PHP. An indexed array stores multiple values in a single variable, with each value accessed by a numeric index starting from 0.

Note: Arrays in PHP are actually ordered maps, making them incredibly versatile and powerful compared to arrays in many other languages.

Creating Indexed Arrays

There are several ways to create indexed arrays in PHP:

<?php // Method 1: Using array() function $fruits = array("Apple", "Banana", "Cherry"); // Method 2: Using short array syntax (recommended) $colors = ["Red", "Green", "Blue"]; // Method 3: Adding elements one by one $numbers = []; $numbers[0] = 10; $numbers[1] = 20; $numbers[2] = 30; // Method 4: PHP automatically assigns indexes $cities = []; $cities[] = "New York"; // index 0 $cities[] = "London"; // index 1 $cities[] = "Tokyo"; // index 2 print_r($fruits); print_r($colors); ?>
Tip: Use the short array syntax [] introduced in PHP 5.4+ for cleaner, more modern code.

Accessing Array Elements

Access array elements using square brackets with the index number:

<?php $fruits = ["Apple", "Banana", "Cherry", "Date"]; // Access individual elements echo $fruits[0]; // Output: Apple echo $fruits[2]; // Output: Cherry // Access last element echo $fruits[count($fruits) - 1]; // Output: Date // Check if index exists before accessing if (isset($fruits[5])) { echo $fruits[5]; } else { echo "Index does not exist"; } ?>

Modifying Array Elements

You can modify existing elements or add new ones:

<?php $numbers = [10, 20, 30]; // Modify existing element $numbers[1] = 25; print_r($numbers); // [10, 25, 30] // Add new element at specific index $numbers[5] = 60; print_r($numbers); // [10, 25, 30, , , 60] // Add element at the end $numbers[] = 70; print_r($numbers); // [10, 25, 30, , , 60, 70] ?>
Warning: When you assign a value to a non-sequential index (like index 5 in the example above), PHP creates undefined indexes in between. Use caution to avoid sparse arrays.

Array Length and Counting

Use count() or sizeof() to get the number of elements:

<?php $animals = ["Dog", "Cat", "Bird", "Fish"]; // Count elements $length = count($animals); echo "Array has $length elements<br>"; // Output: 4 // sizeof() is an alias of count() echo sizeof($animals); // Output: 4 // Empty array $empty = []; echo count($empty); // Output: 0 ?>

Looping Through Arrays

There are multiple ways to iterate over indexed arrays:

<?php $fruits = ["Apple", "Banana", "Cherry", "Date"]; // Method 1: for loop (when you need the index) for ($i = 0; $i < count($fruits); $i++) { echo "$i: $fruits[$i]<br>"; } // Method 2: foreach loop (most common) foreach ($fruits as $fruit) { echo "$fruit<br>"; } // Method 3: foreach with index foreach ($fruits as $index => $fruit) { echo "$index: $fruit<br>"; } // Method 4: while loop $i = 0; while ($i < count($fruits)) { echo $fruits[$i] . "<br>"; $i++; } ?>
Tip: Use foreach for most array iterations - it's cleaner and more efficient than for loops.

Adding and Removing Elements

PHP provides built-in functions to add and remove elements:

<?php $stack = ["Apple", "Banana"]; // Add to end array_push($stack, "Cherry"); // Or use: $stack[] = "Cherry"; print_r($stack); // ["Apple", "Banana", "Cherry"] // Remove from end $last = array_pop($stack); echo $last; // Cherry print_r($stack); // ["Apple", "Banana"] // Add to beginning array_unshift($stack, "Grape"); print_r($stack); // ["Grape", "Apple", "Banana"] // Remove from beginning $first = array_shift($stack); echo $first; // Grape print_r($stack); // ["Apple", "Banana"] ?>

Multi-dimensional Arrays

Arrays can contain other arrays, creating multi-dimensional structures:

<?php // 2D array (matrix) $matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; // Access elements echo $matrix[0][0]; // 1 echo $matrix[1][2]; // 6 echo $matrix[2][1]; // 8 // Loop through 2D array foreach ($matrix as $row) { foreach ($row as $value) { echo "$value "; } echo "<br>"; } // 3D array example $data = [ [ [1, 2], [3, 4] ], [ [5, 6], [7, 8] ] ]; echo $data[1][0][1]; // 6 ?>

Array as Stack or Queue

Arrays can be used to implement stack (LIFO) and queue (FIFO) data structures:

<?php // Stack (Last In, First Out) $stack = []; array_push($stack, "First"); array_push($stack, "Second"); array_push($stack, "Third"); echo array_pop($stack); // Third echo array_pop($stack); // Second // Queue (First In, First Out) $queue = []; array_push($queue, "First"); array_push($queue, "Second"); array_push($queue, "Third"); echo array_shift($queue); // First echo array_shift($queue); // Second ?>
Exercise:
  1. Create an array of your 5 favorite movies
  2. Add a new movie to the beginning of the array
  3. Remove the last movie from the array
  4. Loop through and display each movie with its position
  5. Create a 2D array representing a tic-tac-toe board (3x3) and display it

Best Practices

  • Use the short array syntax [] for cleaner code
  • Check if an index exists with isset() before accessing
  • Use foreach instead of for when you don't need the index
  • Avoid creating sparse arrays (arrays with gaps in indexes)
  • Use array_push() and array_pop() for better readability when implementing stacks
  • Store array length in a variable when using it multiple times in loops

Common Mistakes to Avoid

Warning:
  • Don't forget arrays start at index 0, not 1
  • Accessing non-existent indexes generates warnings
  • Using count() inside loop conditions is inefficient
  • Modifying an array while iterating over it can cause unexpected behavior

Summary

In this lesson, you learned:

  • How to create indexed arrays using multiple methods
  • How to access, modify, and add array elements
  • Different ways to loop through arrays
  • How to add and remove elements from arrays
  • Working with multi-dimensional arrays
  • Using arrays as stacks and queues

Indexed arrays are fundamental to PHP programming. Master them well, as they form the basis for more complex data structures!

ES
Edrees Salih
19 hours ago

We are still cooking the magic in the way!