Monday, August 18, 2025
0 comments

Master PHP from Basics to Advanced: Module 5 - Mastering PHP Arrays & Collections with Real-Life Examples and PHP 8 Features

 Introduction

Welcome to Module 5: Mastering PHP Arrays & Collections in our Master PHP from Basics to Advanced series! Arrays are one of PHP’s most powerful features, enabling you to store, manipulate, and process collections of data efficiently. In this module, we’ll cover indexed, associative, and multidimensional arrays, array functions (like array_map and array_filter), iterating arrays, sorting arrays, and the modern PHP 8 array unpacking feature.PHP powers over 78% of websites (as of August 2025), including platforms like WordPress, Laravel, and Joomla. Arrays are critical for tasks like managing user data, processing form inputs, and generating dynamic content. This tutorial is designed to be engaging, practical, and SEO-friendly, with real-life examples, pros, cons, alternatives, and best practices. Whether you’re a beginner building a shopping cart or an advanced developer optimizing data processing, this guide will empower you to harness PHP arrays effectively.Let’s dive into the world of arrays and collections to create dynamic, scalable web applications!
Module 5: Mastering PHP Arrays & Collections1. Indexed, Associative & Multidimensional ArraysArrays in PHP are versatile data structures that store multiple values. They can be indexed (numeric keys), associative (string keys), or multidimensional (arrays within arrays).Indexed ArraysIndexed arrays use numeric keys, starting from 0 by default.Syntax:
php
$array = [value1, value2, value3];
Example:
php
<?php
$fruits = ["apple", "banana", "orange"];
echo $fruits[0]; // Output: apple
?>
Real-Life Example: Display a list of recent blog posts:
php
<?php
$posts = ["Introduction to PHP", "PHP Arrays", "PHP Functions"];
echo "<ul>";
for ($i = 0; $i < count($posts); $i++) {
    echo "<li>$posts[$i]</li>";
}
echo "</ul>";
// Output:
// <ul>
// <li>Introduction to PHP</li>
// <li>PHP Arrays</li>
// <li>PHP Functions</li>
// </ul>
?>
Associative ArraysAssociative arrays use string keys for key-value pairs.Syntax:
php
$array = ["key1" => value1, "key2" => value2];
Example:
php
<?php
$user = ["name" => "Alice", "age" => 25, "email" => "alice@example.com"];
echo "Name: {$user['name']}, Age: {$user['age']}";
// Output: Name: Alice, Age: 25
?>
Real-Life Example: Manage user profile data:
php
<?php
$profile = [
    "username" => "john_doe",
    "role" => "admin",
    "last_login" => "2025-08-18"
];
echo "Welcome, {$profile['username']} ({$profile['role']})! Last login: {$profile['last_login']}";
// Output: Welcome, john_doe (admin)! Last login: 2025-08-18
?>
Multidimensional ArraysMultidimensional arrays are arrays containing other arrays, useful for complex data structures.Example:
php
<?php
$students = [
    ["name" => "John", "grades" => [85, 90, 88]],
    ["name" => "Alice", "grades" => [92, 95, 87]]
];
echo "{$students[0]['name']}'s first grade: {$students[0]['grades'][0]}";
// Output: John's first grade: 85
?>
Real-Life Example: E-commerce product catalog:
php
<?php
$products = [
    "electronics" => [
        ["name" => "Laptop", "price" => 999.99, "stock" => 10],
        ["name" => "Phone", "price" => 499.99, "stock" => 20]
    ],
    "clothing" => [
        ["name" => "T-Shirt", "price" => 19.99, "stock" => 50]
    ]
];
echo "{$products['electronics'][0]['name']}: \${$products['electronics'][0]['price']}";
// Output: Laptop: $999.99
?>
Pros:
  • Indexed arrays are simple for ordered lists.
  • Associative arrays are intuitive for key-value data.
  • Multidimensional arrays handle complex, hierarchical data.
Cons:
  • Large arrays can be memory-intensive.
  • Multidimensional arrays can become hard to manage.
  • Undefined index errors are common if keys are not validated.
Best Practices:
  • Use isset() or array_key_exists() to check for keys.
  • Keep array structures consistent for predictability.
  • Use meaningful keys in associative arrays.
Example: Shopping Cart Summary:
php
<?php
$cart = [
    ["item" => "Book", "price" => 15.99, "quantity" => 2],
    ["item" => "Pen", "price" => 2.99, "quantity" => 5]
];
$total = 0;
foreach ($cart as $item) {
    $total += $item["price"] * $item["quantity"];
}
echo "Cart Total: $" . number_format($total, 2);
// Output: Cart Total: $30.93
?>

2. Array Functions (array_map, array_filter, etc.)PHP provides a rich set of array functions to manipulate and process arrays efficiently. Key functions include array_map, array_filter, array_reduce, array_merge, and more.array_mapApplies a callback function to each element of an array, returning a new array.Example:
php
<?php
$numbers = [1, 2, 3, 4];
$doubled = array_map(fn($n) => $n * 2, $numbers);
print_r($doubled); // Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )
?>
Real-Life Example: Apply a discount to product prices:
php
<?php
$products = [10.00, 20.00, 30.00];
$discounted = array_map(fn($price) => $price * 0.9, $products);
print_r($discounted); // Output: Array ( [0] => 9 [1] => 18 [2] => 27 )
?>
array_filterFilters array elements based on a callback, returning a new array.Example:
php
<?php
$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, fn($n) => $n % 2 === 0);
print_r($even); // Output: Array ( [1] => 2 [3] => 4 )
?>
Real-Life Example: Filter out-of-stock products:
php
<?php
$inventory = [
    ["name" => "Laptop", "stock" => 0],
    ["name" => "Phone", "stock" => 10],
    ["name" => "Tablet", "stock" => 5]
];
$inStock = array_filter($inventory, fn($item) => $item["stock"] > 0);
print_r($inStock);
// Output: Array with Phone and Tablet
?>
array_reduceReduces an array to a single value using a callback.Example:
php
<?php
$numbers = [1, 2, 3, 4];
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
echo $sum; // Output: 10
?>
Real-Life Example: Calculate total order value:
php
<?php
$cart = [
    ["price" => 19.99, "quantity" => 2],
    ["price" => 5.99, "quantity" => 3]
];
$total = array_reduce($cart, fn($carry, $item) => $carry + ($item["price"] * $item["quantity"]), 0);
echo "Total: $" . number_format($total, 2); // Output: Total: $57.95
?>
Other Useful Array Functions
  • array_merge: Combines multiple arrays.
  • array_keys: Returns all keys of an array.
  • array_values: Returns all values of an array.
  • array_unique: Removes duplicate values.
Example:
php
<?php
$array1 = ["a" => 1, "b" => 2];
$array2 = ["c" => 3];
$merged = array_merge($array1, $array2);
print_r($merged); // Output: Array ( [a] => 1 [b] => 2 [c] => 3 )
?>
Pros:
  • Array functions simplify complex operations.
  • Functional programming style improves readability.
  • Efficient for large datasets.
Cons:
  • Some functions (e.g., array_map) create new arrays, increasing memory usage.
  • Callback functions can be less intuitive for beginners.
Best Practices:
  • Use arrow functions (PHP 7.4+) for concise callbacks.
  • Validate array inputs to prevent errors.
  • Combine functions for complex operations (e.g., filter then map).
Example: Process User Feedback:
php
<?php
$feedback = [
    ["user" => "John", "rating" => 5, "comment" => "Great!"],
    ["user" => "Alice", "rating" => 3, "comment" => ""],
    ["user" => "Bob", "rating" => 4, "comment" => "Good service"]
];
$highRated = array_filter($feedback, fn($item) => $item["rating"] >= 4);
$comments = array_map(fn($item) => "{$item['user']}: {$item['comment']}", $highRated);
echo implode("<br>", $comments);
// Output:
// John: Great!
// Bob: Good service
?>

3. Iterating ArraysIterating arrays allows you to process each element using loops or array functions.Using foreachThe foreach loop is the most common way to iterate arrays.Example:
php
<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
    echo "$color<br>";
}
// Output:
// red
// green
// blue
?>
Real-Life Example: Display a user list:
php
<?php
$users = [
    ["name" => "John", "email" => "john@example.com"],
    ["name" => "Alice", "email" => "alice@example.com"]
];
echo "<table border='1'>";
echo "<tr><th>Name</th><th>Email</th></tr>";
foreach ($users as $user) {
    echo "<tr><td>{$user['name']}</td><td>{$user['email']}</td></tr>";
}
echo "</table>";
// Output: HTML table with user data
?>
Using for with Indexed ArraysUse for for indexed arrays when index access is needed.Example:
php
<?php
$numbers = [10, 20, 30];
for ($i = 0; $i < count($numbers); $i++) {
    echo "Index $i: $numbers[$i]<br>";
}
// Output:
// Index 0: 10
// Index 1: 20
// Index 2: 30
?>
Using array_walkarray_walk applies a callback to each element, modifying the array in place.Example:
php
<?php
$prices = [10.00, 20.00, 30.00];
array_walk($prices, function(&$price) {
    $price *= 1.1; // Apply 10% increase
});
print_r($prices); // Output: Array ( [0] => 11 [1] => 22 [2] => 33 )
?>
Real-Life Example: Format product names:
php
<?php
$products = ["laptop", "phone", "tablet"];
array_walk($products, function(&$product) {
    $product = ucfirst($product);
});
print_r($products); // Output: Array ( [0] => Laptop [1] => Phone [2] => Tablet )
?>
Pros:
  • foreach is simple and readable for most use cases.
  • array_walk modifies arrays in place, saving memory.
  • for provides precise control over iteration.
Cons:
  • for loops require manual index management.
  • array_walk can be less intuitive than foreach.
Best Practices:
  • Use foreach for most array iterations.
  • Cache count() in for loops to optimize performance.
  • Use array_walk for in-place modifications.
Example: Generate Product Cards:
php
<?php
$products = [
    ["name" => "Laptop", "price" => 999.99],
    ["name" => "Phone", "price" => 499.99]
];
echo "<div class='products'>";
foreach ($products as $product) {
    echo "<div class='product-card'>";
    echo "<h2>{$product['name']}</h2>";
    echo "<p>Price: $" . number_format($product['price'], 2) . "</p>";
    echo "</div>";
}
echo "</div>";
?>

4. Sorting ArraysPHP provides functions to sort arrays by keys or values, in ascending or descending order.Common Sorting Functions
  • sort: Sorts indexed arrays in ascending order.
  • rsort: Sorts in descending order.
  • asort, arsort: Sort associative arrays by value.
  • ksort, krsort: Sort associative arrays by key.
  • usort: Custom sorting with a callback.
Example: Basic Sorting:
php
<?php
$numbers = [3, 1, 4, 2];
sort($numbers);
print_r($numbers); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
?>
Real-Life Example: Sort products by price:
php
<?php
$products = [
    ["name" => "Laptop", "price" => 999.99],
    ["name" => "Phone", "price" => 499.99],
    ["name" => "Tablet", "price" => 299.99]
];
usort($products, fn($a, $b) => $a["price"] <=> $b["price"]);
print_r($products);
// Output: Sorted by price (Tablet, Phone, Laptop)
?>
Example: Sort Users by Name:
php
<?php
$users = [
    "bob" => ["name" => "Bob Smith", "age" => 30],
    "alice" => ["name" => "Alice Johnson", "age" => 25]
];
asort($users);
print_r($users);
// Output: Sorted by name (Alice, Bob)
?>
Pros:
  • Built-in functions handle common sorting needs.
  • usort allows flexible, custom sorting.
  • Efficient for small to medium datasets.
Cons:
  • Sorting large arrays can be slow.
  • usort callbacks require careful implementation.
Best Practices:
  • Use sort/asort for simple sorting.
  • Use usort for complex criteria.
  • Avoid modifying arrays during sorting.
Example: Multi-Criteria Sorting:
php
<?php
$products = [
    ["name" => "Laptop", "price" => 999.99, "stock" => 10],
    ["name" => "Phone", "price" => 999.99, "stock" => 5],
    ["name" => "Tablet", "price" => 299.99, "stock" => 20]
];
usort($products, function($a, $b) {
    if ($a["price"] === $b["price"]) {
        return $b["stock"] <=> $a["stock"]; // Sort by stock if prices are equal
    }
    return $a["price"] <=> $b["price"];
});
print_r($products);
// Output: Tablet, Phone, Laptop
?>

5. PHP 8: Array UnpackingIntroduced in PHP 7.4 and enhanced in PHP 8, array unpacking uses the ... operator to merge arrays or extract elements.Example: Merge Arrays:
php
<?php
$array1 = [1, 2];
$array2 = [3, 4];
$combined = [...$array1, ...$array2];
print_r($combined); // Output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
?>
Example: Unpack in Function Arguments:
php
<?php
function add($a, $b, $c) {
    return $a + $b + $c;
}
$numbers = [1, 2, 3];
echo add(...$numbers); // Output: 6
?>
Real-Life Example: Combine user preferences:
php
<?php
$defaultPrefs = ["theme" => "light", "notifications" => true];
$userPrefs = ["language" => "en"];
$settings = [...$defaultPrefs, ...$userPrefs];
print_r($settings);
// Output: Array ( [theme] => light [notifications] => 1 [language] => en )
?>
Pros:
  • Simplifies array merging and argument passing.
  • Improves readability for dynamic data.
  • Works with both indexed and associative arrays.
Cons:
  • Requires PHP 7.4+ (enhanced in PHP 8).
  • Can overwrite keys in associative arrays.
Best Practices:
  • Use unpacking for concise array operations.
  • Be cautious with key conflicts in associative arrays.
  • Combine with named arguments for clarity.
Example: Dynamic Form Processing:
php
<?php
$requiredFields = ["name", "email"];
$optionalFields = ["phone", "address"];
$allFields = [...$requiredFields, ...$optionalFields];
$errors = [];
foreach ($allFields as $field) {
    if (empty($_POST[$field])) {
        $errors[] = "$field is required";
    }
}
echo empty($errors) ? "Form valid" : implode("<br>", $errors);
?>

Advanced Scenarios
  1. Dynamic Product Filter: Filter and sort products based on user input:
    php
    <?php
    $products = [
        ["name" => "Laptop", "price" => 999.99, "category" => "Electronics"],
        ["name" => "T-Shirt", "price" => 19.99, "category" => "Clothing"],
        ["name" => "Phone", "price" => 499.99, "category" => "Electronics"]
    ];
    $category = $_GET['category'] ?? "all";
    $filtered = array_filter($products, fn($product) => $category === "all" || $product["category"] === $category);
    usort($filtered, fn($a, $b) => $a["price"] <=> $b["price"]);
    echo "<ul>";
    foreach ($filtered as $product) {
        echo "<li>{$product['name']} (\${$product['price']})</li>";
    }
    echo "</ul>";
    ?>
  2. Nested Data Processing: Process a multidimensional array for reporting:
    php
    <?php
    $sales = [
        "2025-08" => [
            ["product" => "Laptop", "amount" => 2000],
            ["product" => "Phone", "amount" => 1500]
        ],
        "2025-07" => [
            ["product" => "Tablet", "amount" => 1000]
        ]
    ];
    $totalByMonth = array_map(fn($month) => array_reduce($month, fn($carry, $item) => $carry + $item["amount"], 0), $sales);
    print_r($totalByMonth);
    // Output: Array ( [2025-08] => 3500 [2025-07] => 1000 )
    ?>
  3. Dynamic Menu with Unpacking: Generate a menu with merged options:
    php
    <?php
    $mainMenu = ["Home", "Products"];
    $userMenu = ["Profile", "Logout"];
    $menu = [...$mainMenu, ...$userMenu];
    echo "<nav><ul>";
    array_walk($menu, fn($item) => print("<li>$item</li>"));
    echo "</ul></nav>";
    ?>

ConclusionCongratulations on mastering Module 5: Mastering PHP Arrays & Collections! You’ve learned to work with indexed, associative, and multidimensional arrays, leverage array functions like array_map and array_filter, iterate arrays, sort arrays, and use PHP 8 array unpacking. Real-life examples like product catalogs, user feedback processing, and dynamic menus show how arrays power modern web applications. By following best practices like key validation and functional programming, you’re ready to write efficient, scalable PHP code.

0 comments:

Featured Post

Master Angular 20 Basics: A Complete Beginner’s Guide with Examples and Best Practices

Welcome to the complete Angular 20 learning roadmap ! This series takes you step by step from basics to intermediate concepts , with hands...

Subscribe

 
Toggle Footer
Top