Arrays - Indexed and Associative Arrays, Looping Arrays, Array Operations

Introduction to Arrays in PHP

Arrays are one of the most fundamental and powerful data structures in programming. In PHP, an array is essentially an ordered map. This means it can hold multiple values under a single variable name. Think of it like a list or a collection of items. Each item in the array has a unique identifier, called an index or a key, which you use to access it. PHP arrays are very flexible; they can hold different data types (integers, strings, objects, even other arrays) and can grow or shrink dynamically.

Understanding arrays is crucial for managing collections of data, such as lists of users, products, or configuration settings. They simplify data manipulation and make your code more organized and efficient. PHP offers two primary types of arrays: indexed arrays and associative arrays.

Indexed Arrays

Indexed arrays are the most common type. In an indexed array, each element is assigned a numerical index, starting from 0 by default. PHP automatically assigns these indices if you don't specify them yourself. This makes them ideal for storing ordered lists of items where the position of the item is important.

Creating Indexed Arrays:

You can create indexed arrays using the `array()` construct or the shorthand `[]` syntax.

Example 1: Using `array()`

<?php
$fruits = array("Apple", "Banana", "Cherry");
?>
  

In this example, "Apple" is at index 0, "Banana" is at index 1, and "Cherry" is at index 2.

Example 2: Using `[]` (shorthand)

<?php
$colors = ["Red", "Green", "Blue"];
?>
  

This achieves the same result as the `array()` construct. "Red" is at index 0, "Green" at 1, and "Blue" at 2.

Adding Elements to an Indexed Array:

You can add new elements to an indexed array by assigning a value to a new index. If you don't specify an index, PHP will automatically assign the next available numerical index.

<?php
$cars = ["Volvo", "BMW"];
$cars[] = "Toyota"; // Adds "Toyota" at index 2
$cars[] = "Honda";  // Adds "Honda" at index 3
print_r($cars);
?>
  

Output:

Array
(
    [0] => Volvo
    [1] => BMW
    [2] => Toyota
    [3] => Honda
)
  

You can also explicitly set an index, but be careful not to overwrite existing elements unless intended.

<?php
$numbers = [10, 20];
$numbers[5] = 50; // Adds 50 at index 5. Indices 3 and 4 will be empty (null).
print_r($numbers);
?>
  

Output:

Array
(
    [0] => 10
    [1] => 20
    [5] => 50
)
  

Accessing Elements:

You access elements in an indexed array by enclosing the index in square brackets `[]` after the array variable name.

<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Output: Apple
echo $fruits[1]; // Output: Banana
?>
  

Associative Arrays

Associative arrays are arrays where you can assign your own keys to elements, instead of relying on numerical indices. These keys are typically strings, making the array more readable and descriptive. They are similar to dictionaries or hash maps in other programming languages. Associative arrays are perfect for storing data that has named properties, like a person's details or configuration options.

Creating Associative Arrays:

You use the `=>` operator to associate a key with a value.

Example 1: Using `array()`

<?php
$person = array(
  "firstName" => "John",
  "lastName" => "Doe",
  "age" => 30
);
?>
  

Here, "firstName", "lastName", and "age" are the keys, and "John", "Doe", and 30 are their corresponding values.

Example 2: Using `[]` (shorthand)

<?php
$student = [
  "name" => "Alice",
  "major" => "Computer Science",
  "gpa" => 3.8
];
?>
  

This syntax is more concise and widely used in modern PHP.

Adding Elements to an Associative Array:

Similar to indexed arrays, you can add new elements by assigning a value to a new key.

<?php
$book = [
  "title" => "The Great Gatsby",
  "author" => "F. Scott Fitzgerald"
];
$book["year"] = 1925; // Adds the 'year' key with value 1925
$book["genre"] = "Fiction"; // Adds the 'genre' key
print_r($book);
?>
  

Output:

Array
(
    [title] => The Great Gatsby
    [author] => F. Scott Fitzgerald
    [year] => 1925
    [genre] => Fiction
)
  

Accessing Elements:

Access elements using the key enclosed in square brackets `[]` after the array variable name.

<?php
$person = [
  "firstName" => "John",
  "lastName" => "Doe",
  "age" => 30
];
echo $person["firstName"]; // Output: John
echo $person["age"];       // Output: 30
?>
  

Mixed Arrays

PHP arrays are very flexible and can even contain a mix of indexed and associative elements. However, this is generally discouraged as it can lead to confusion and make your code harder to maintain. It's best practice to stick to either purely indexed or purely associative arrays for clarity.

<?php
$mixedArray = [
  "name" => "Test",
  0 => "First element",
  "another_key" => "Some value",
  1 => "Second element"
];
print_r($mixedArray);
?>
  

Output:

Array
(
    [name] => Test
    [0] => First element
    [another_key] => Some value
    [1] => Second element
)
  

Notice how the numerical indices are treated separately from the string keys.

Looping Through Arrays

Iterating over arrays is a common task. PHP provides several loops that are well-suited for this purpose. The choice of loop often depends on whether you need the index/key or just the values.

1. `for` loop (for Indexed Arrays)

The `for` loop is typically used with indexed arrays when you know the exact number of elements or can easily determine it using `count()`.

<?php
$colors = ["Red", "Green", "Blue"];
$arrayLength = count($colors); // Get the number of elements

for($i = 0; $i < $arrayLength; $i++) {
  echo "Element at index " . $i . ": " . $colors[$i] . "<br>";
}
?>
  

Output:

Element at index 0: Red
Element at index 1: Green
Element at index 2: Blue
  

Shortcut: Use `count()` to get the array size. Remember that indexed arrays start at index 0.

2. `foreach` loop (for Both Indexed and Associative Arrays)

The `foreach` loop is the most versatile and commonly used loop for arrays in PHP. It can iterate over both indexed and associative arrays, providing either just the values or both the keys and values.

a) Iterating over values only:

<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
  echo $fruit . "<br>";
}
?>
  

Output:

Apple
Banana
Cherry
  

b) Iterating over keys and values (for associative arrays):

<?php
$person = [
  "firstName" => "John",
  "lastName" => "Doe",
  "age" => 30
];
foreach ($person as $key => $value) {
  echo $key . ": " . $value . "<br>";
}
?>
  

Output:

firstName: John
lastName: Doe
age: 30
  

c) Iterating over keys and values (for indexed arrays):

While `foreach` is primarily known for associative arrays, it works perfectly for indexed arrays too, giving you the numerical index as the key.

<?php
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $index => $color) {
  echo "Index " . $index . ": " . $color . "<br>";
}
?>
  

Output:

Index 0: Red
Index 1: Green
Index 2: Blue
  

3. `while` loop (less common for arrays, but possible)

A `while` loop can also be used, often in conjunction with functions like `each()` (though `each()` is deprecated in PHP 8.0 and later) or by manually managing an index. `foreach` is generally preferred for its simplicity and readability.

Array Operations

PHP provides a rich set of built-in functions for manipulating arrays. These operations allow you to add, remove, search, sort, and combine arrays efficiently.

1. Adding Elements

As shown earlier, you can add elements using `[]` for both indexed and associative arrays.

`array_push()`: Adds one or more elements to the end of an indexed array.

<?php
$stack = ["Red", "Green"];
array_push($stack, "Blue", "Yellow");
print_r($stack);
?>
  

Output:

Array
(
    [0] => Red
    [1] => Green
    [2] => Blue
    [3] => Yellow
)
  

2. Removing Elements

`unset()`: Removes a specific element by its key/index or the entire array.

<?php
$person = ["name" => "Alice", "age" => 25, "city" => "New York"];
unset($person["age"]); // Removes the 'age' element
print_r($person);

$numbers = [1, 2, 3, 4];
unset($numbers[1]); // Removes element at index 1 (value 2)
print_r($numbers);
?>
  

Output:

Array
(
    [name] => Alice
    [city] => New York
)
Array
(
    [0] => 1
    [2] => 3
    [3] => 4
)
  

Note that `unset()` on an indexed array leaves "holes" in the index sequence. Use `array_values()` afterwards if you need re-indexed contiguous keys.

`array_pop()`: Removes the last element from an indexed array and returns its value.

<?php
$colors = ["Red", "Green", "Blue"];
$lastColor = array_pop($colors);
echo $lastColor; // Output: Blue
print_r($colors); // Output: Array ( [0] => Red [1] => Green )
?>
  

`array_shift()`: Removes the first element from an indexed array and returns its value. It also re-indexes the remaining elements.

<?php
$colors = ["Red", "Green", "Blue"];
$firstColor = array_shift($colors);
echo $firstColor; // Output: Red
print_r($colors); // Output: Array ( [0] => Green [1] => Blue )
?>
  

`array_splice()`: Removes a portion of the array and replaces it with something else. It can remove elements and optionally insert new ones. It re-indexes the array.

<?php
$input = array("red", "green", "blue", "yellow", "brown", "black");
// Remove "blue", "yellow", "brown" and insert "purple", "orange"
$replacement = array("purple", "orange");
$result = array_splice($input, 2, 3, $replacement); // Start at index 2, remove 3 elements, insert $replacement
print_r($input); // The modified original array
print_r($result); // The removed elements
?>
  

Output:

Array
(
    [0] => red
    [1] => green
    [2] => purple
    [3] => orange
    [4] => black
)
Array
(
    [0] => blue
    [1] => yellow
    [2] => brown
)
  

3. Searching Arrays

`in_array()`: Checks if a value exists in an array. Returns `true` or `false`.

<?php
$fruits = ["Apple", "Banana", "Cherry"];
if (in_array("Banana", $fruits)) {
  echo "Banana is in the list";
} else {
  echo "Banana is not in the list";
}
?>
  

`array_search()`: Searches an array for a given value and returns the key of the first matching element. Returns `false` if the value is not found.

<?php
$fruits = ["Apple", "Banana", "Cherry"];
$key = array_search("Banana", $fruits);
if ($key !== false) {
  echo "Banana found at key: " . $key; // Output: Banana found at key: 1
}
?>
  

`key_exists()`: Checks if the given key or index exists in the array.

<?php
$person = ["name" => "Alice", "age" => 25];
if (key_exists("age", $person)) {
  echo "Age key exists."; // Output: Age key exists.
}
if (key_exists(0, $person)) {
  echo "Index 0 exists.";
} else {
  echo "Index 0 does not exist.";
}
?>
  

4. Sorting Arrays

PHP offers various sorting functions for both indexed and associative arrays. Sorting affects the keys differently for each type.

For Indexed Arrays:

  • `sort()`: Sorts an indexed array in ascending order. Re-indexes numerically.
  • `rsort()`: Sorts an indexed array in descending order. Re-indexes numerically.
  • `asort()`: Sorts an associative array in ascending order, according to the value. Maintains key association.
  • `arsort()`: Sorts an associative array in descending order, according to the value. Maintains key association.
  • `ksort()`: Sorts an associative array in ascending order, according to the key.
  • `krsort()`: Sorts an associative array in descending order, according to the key.

Example with `sort()` (Indexed Array):

<?php
$numbers = [4, 2, 8, 6];
sort($numbers);
print_r($numbers); // Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
?>
  

Example with `asort()` (Associative Array):

<?php
$age = ["Peter" => 35, "Ben" => 37, "Joe" => 43];
asort($age);
print_r($age);
// Output: Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 ) - Sorted by value, keys remain associated
?>
  

Example with `ksort()` (Associative Array):

<?php
$age = ["Peter" => 35, "Ben" => 37, "Joe" => 43];
ksort($age);
print_r($age);
// Output: Array ( [Ben] => 37 [Joe] => 43 [Peter] => 35 ) - Sorted by key, values remain associated
?>
  
Sorting Shortcut:
  • `sort()` / `rsort()`: For indexed arrays, sorts by value, re-indexes.
  • `asort()` / `arsort()`: For associative arrays, sorts by value, keeps keys.
  • `ksort()` / `krsort()`: For associative arrays, sorts by key, keeps values.

5. Merging and Combining Arrays

`array_merge()`: Merges one or more arrays. If the arrays have the same string keys, the later value overwrites the earlier one. For numeric keys, the values are appended and re-indexed.

<?php
$arr1 = ["color" => "red", 0 => "apple"];
$arr2 = ["color" => "blue", 1 => "banana"];
$merged = array_merge($arr1, $arr2);
print_r($merged);
?>
  

Output:

Array
(
    [color] => blue
    [0] => apple
    [1] => banana
)
  

Notice how "color" from `$arr2` overwrites "color" from `$arr1`. The numeric keys are re-indexed starting from 0.

`+` operator (Union): Combines arrays. If the arrays have the same keys (string or numeric), the element from the first array is kept, and the element from the second array is ignored. It does NOT re-index numeric keys.

<?php
$arr1 = ["color" => "red", 0 => "apple"];
$arr2 = ["color" => "blue", 1 => "banana"];
$union = $arr1 + $arr2;
print_r($union);
?>
  

Output:

Array
(
    [color] => red
    [0] => apple
    [1] => banana
)
  

Here, "color" from `$arr1` is kept. The numeric key `1` from `$arr2` is preserved because `$arr1` doesn't have a key `1`.

Merge vs. Union:
  • `array_merge()`: Overwrites duplicate string keys, re-indexes numeric keys.
  • `+` operator: Keeps the first value for duplicate keys (string or numeric), does NOT re-index numeric keys.

6. Counting Elements

`count()`: Returns the number of elements in an array.

<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo count($fruits); // Output: 3

$person = ["name" => "Alice", "age" => 25];
echo count($person); // Output: 2
?>
  

`sizeof()`: This is an alias of `count()`. They function identically.

7. Re-indexing Arrays

`array_values()`: Returns all the values from an array and adds next keys to the array with numerical keys starting from 0. Useful after using `unset()` on indexed arrays to remove gaps.

<?php
$numbers = [0 => 10, 5 => 50, 2 => 20];
print_r($numbers); // Output: Array ( [0] => 10 [5] => 50 [2] => 20 )
$newNumbers = array_values($numbers);
print_r($newNumbers); // Output: Array ( [0] => 10 [1] => 50 [2] => 20 )
?>
  

8. Extracting Keys and Values

`array_keys()`: Returns all the keys of an array.

<?php
$person = ["firstName" => "John", "lastName" => "Doe", "age" => 30];
$keys = array_keys($person);
print_r($keys); // Output: Array ( [0] => firstName [1] => lastName [2] => age )
?>
  

`array_values()`: As seen before, returns all the values.

9. Array Chunking

`array_chunk()`: Splits an array into chunks of a specified size.

<?php
$input_array = ['a', 'b', 'c', 'd', 'e', 'f'];
$chunk_size = 2;
$result = array_chunk($input_array, $chunk_size);
print_r($result);
?>
  

Output:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
            [1] => f
        )
)
  

The second parameter can be `true` to create associative arrays where the keys are preserved.

Working with Multi-dimensional Arrays

Arrays can contain other arrays, leading to multi-dimensional arrays. These are useful for representing complex data structures like tables or nested lists.

Example: A 2D array representing a matrix or a list of records

<?php
$students = [
  [
    "id" => 101,
    "name" => "Alice",
    "major" => "Computer Science"
  ],
  [
    "id" => 102,
    "name" => "Bob",
    "major" => "Physics"
  ],
  [
    "id" => 103,
    "name" => "Charlie",
    "major" => "Chemistry"
  ]
];

// Accessing an element: Get Bob's major
echo $students[1]["major"]; // Output: Physics

// Looping through a multi-dimensional array
foreach ($students as $student) {
  echo "ID: " . $student["id"] . ", Name: " . $student["name"] . ", Major: " . $student["major"] . "<br>";
}
?>
  

Output:

ID: 101, Name: Alice, Major: Computer Science
ID: 102, Name: Bob, Major: Physics
ID: 103, Name: Charlie, Major: Chemistry
  

Multi-dimensional arrays are essential for organizing structured data. You can have arrays within arrays within arrays, creating complex data models.