Skip to Content
Course content

55: Multidimensional Array Manipulation

Click on the "Edit" button in the top corner of the screen to edit your slide content.

By now, you're comfortable with basic arrays, but real-world data is rarely a flat list. Whether you're pulling a JSON response from an API or fetching a complex dataset from a database, you're going to be dealing with arrays inside arrays. It can get messy quickly if you don't have a strategy for navigating them.

How do I loop through these things without getting lost in the indexes?

The most common way to handle this is by nesting foreach loops. The trick is to give your variables clear, descriptive names so you don't forget which "level" of the array you're currently inside. If you just use $val and $val2, you'll be staring at your screen in confusion five minutes later.

$catalog = [
    'electronics' => [
        ['name' => 'Laptop', 'price' => 1200, 'tags' => ['work', 'tech']],
        ['name' => 'Phone', 'price' => 800, 'tags' => ['mobile', 'tech']],
    ],
    'furniture' => [
        ['name' => 'Desk', 'price' => 300, 'tags' => ['office', 'home']],
        ['name' => 'Chair', 'price' => 150, 'tags' => ['office', 'home']],
    ],
];

foreach ($catalog as $category => $products) {
    echo "Category: $category\n";
    foreach ($products as $product) {
        echo "- " . $product['name'] . " costs $" . $product['price'] . "\n";
    }
}

In this example, the outer loop handles the categories, and the inner loop handles the individual product arrays. It's a simple pattern, but it's the bread and butter of multidimensional manipulation.

What's the best way to sort a list of arrays by a specific value?

You can't use sort() or asort() here because PHP wouldn't know which key inside the nested array you want to sort by. For this, you need usort() (user-defined sort). I always recommend using the spaceship operator <=> introduced in PHP 7; it makes the comparison logic incredibly clean.

$products = [
    ['name' => 'Laptop', 'price' => 1200],
    ['name' => 'Phone', 'price' => 800],
    ['name' => 'Mouse', 'price' => 25],
];

// Sort by price: Lowest to Highest
usort($products, function($a, $b) {
    return $a['price'] <=> $b['price'];
});

print_r($products);

The usort function takes the array and a callback. Inside that callback, PHP passes two elements (which are themselves arrays in this case). The spaceship operator returns -1, 0, or 1 based on the comparison, which is exactly what usort expects to determine the order.

How do I update a value buried deep inside a nested array?

This is where a lot of developers trip up. If you loop through a multidimensional array and change a value, you're often changing a copy of that value, not the original array. To actually modify the data, you have to use a reference by adding an ampersand & before the variable in your foreach loop.

$inventory = [
    ['id' => 1, 'name' => 'Laptop', 'stock' => 5],
    ['id' => 2, 'name' => 'Phone', 'stock' => 10],
];

// We want to add 1 to the stock of the Laptop (id 1)
foreach ($inventory as &$item) {
    if ($item['id'] === 1) {
        $item['stock']++; 
    }
}
unset($item); // Always unset a reference after the loop!

Notice the &$item. This tells PHP, "Don't make a copy of this array element; give me a direct pointer to it." Also, I added an unset($item) at the end. This is a professional habit you should develop; if you reuse the $item variable later in your script, you might accidentally overwrite the last element of your array because the reference is still active.

Can I filter a multidimensional array based on a nested condition?

Yes, and array_filter() is your best friend here. It allows you to define a rule, and PHP will return a new array containing only the elements that meet that rule. I find this much cleaner than creating an empty array and manually pushing items into it with another loop.

$users = [
    ['name' => 'Alice', 'role' => 'admin', 'active' => true],
    ['name' => 'Bob', 'role' => 'editor', 'active' => false],
    ['name' => 'Charlie', 'role' => 'admin', 'active' => false],
];

$activeAdmins = array_filter($users, function($user) {
    return $user['role'] === 'admin' && $user['active'] === true;
});

print_r($activeAdmins);

This effectively strips out everyone who isn't an active admin. One thing to keep in mind: array_filter preserves the original keys. If you need the resulting array to be re-indexed from 0, wrap the whole thing in array_values().




📋 Practical Task

The Product Inventory Price Adjustment Tool

You have been given a multidimensional array representing a store's inventory. Your task is to write a script that performs the following logic:

  1. Create a multidimensional array called $inventory containing at least 4 products. Each product should be an array with the keys: 'name' (string), 'category' (string), and 'price' (float).
  2. Use a foreach loop with a reference to find all products in the 'Electronics' category and apply a 10% discount to their price.
  3. Use usort() to sort the entire inventory from the most expensive product to the cheapest.
  4. Print the final adjusted and sorted array using print_r().

Example data structure to get you started:

$inventory = [
    ['name' => 'Headphones', 'category' => 'Electronics', 'price' => 100.00],
    ['name' => 'Coffee Mug', 'category' => 'Kitchen', 'price' => 15.00],
    // ... add more
];
Rating
0 0

There are no comments for now.

to be the first to leave a comment.