PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
55: Multidimensional Array Manipulation
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:
- Create a multidimensional array called
$inventorycontaining at least 4 products. Each product should be an array with the keys:'name'(string),'category'(string), and'price'(float). - Use a
foreachloop with a reference to find all products in the 'Electronics' category and apply a 10% discount to their price. - Use
usort()to sort the entire inventory from the most expensive product to the cheapest. - 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
];There are no comments for now.