π PHP Advanced Arrays: Your Magic Toolbox
Imagine you have a toy box full of toys. Sometimes you want to:
- Pick only the red toys (filtering)
- Paint all toys blue (mapping)
- Count how many toys you have total (reduce)
- Take toys out and name them (destructuring)
- Pour more toys into your box (spread operator)
- Check if a toy exists or is empty (isset, empty, is_null)
Letβs learn these superpowers for PHP arrays! π¦Έ
π Array Filtering: Picking Only What You Want
Story Time: You have a basket of fruits. You only want the ripe ones. Filtering helps you pick just those!
The Magic Function: array_filter()
$numbers = [1, 2, 3, 4, 5, 6];
// Keep only even numbers
$evens = array_filter($numbers, function($n) {
return $n % 2 === 0;
});
// Result: [2, 4, 6]
How It Works
graph TD A["Array: 1,2,3,4,5,6"] --> B{Is it even?} B -->|Yes| C["Keep it!"] B -->|No| D["Skip it!"] C --> E["Result: 2,4,6"]
Real Example: Filter Active Users
$users = [
['name' => 'Ali', 'active' => true],
['name' => 'Sara', 'active' => false],
['name' => 'Max', 'active' => true]
];
$activeUsers = array_filter($users, function($u) {
return $u['active'] === true;
});
// Gets: Ali and Max
Pro Tip: Without a callback, array_filter() removes βfalsyβ values (0, ββ, null, false).
π¨ Array Mapping: Transform Everything!
Story Time: Imagine you have plain cupcakes. You want to add frosting to ALL of them. Thatβs mapping!
The Magic Function: array_map()
$numbers = [1, 2, 3];
// Double every number
$doubled = array_map(function($n) {
return $n * 2;
}, $numbers);
// Result: [2, 4, 6]
How It Works
graph TD A["Input: 1, 2, 3"] --> B["Apply: n Γ 2"] B --> C["Output: 2, 4, 6"]
Real Example: Get All Names
$users = [
['name' => 'Ali', 'age' => 25],
['name' => 'Sara', 'age' => 30],
['name' => 'Max', 'age' => 22]
];
$names = array_map(function($user) {
return $user['name'];
}, $users);
// Result: ['Ali', 'Sara', 'Max']
Key Difference:
filter= picks some itemsmap= changes ALL items
π Array Reduce: Squash Into One Value
Story Time: You have coins: 5Β’, 10Β’, 25Β’. You want to know the TOTAL. Reduce adds them all up!
The Magic Function: array_reduce()
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, function($carry, $n) {
return $carry + $n;
}, 0);
// Result: 15
How It Works
graph TD A["Start: 0"] --> B["0 + 1 = 1"] B --> C["1 + 2 = 3"] C --> D["3 + 3 = 6"] D --> E["6 + 4 = 10"] E --> F["10 + 5 = 15"] F --> G["Final: 15"]
Understanding the Parameters
| Part | What It Does |
|---|---|
$carry |
Running total (accumulator) |
$n |
Current item being processed |
0 |
Starting value |
Real Example: Build a String
$words = ['Hello', 'World', 'PHP'];
$sentence = array_reduce($words, function($c, $w) {
return $c . ' ' . $w;
}, '');
// Result: " Hello World PHP"
π¦ Array Destructuring: Unpack Like Magic
Story Time: You get a gift box with 3 items inside. Instead of calling them βitem 1, item 2β, you give them nice names!
Basic Destructuring
$coords = [10, 20, 30];
// Old way
$x = $coords[0];
$y = $coords[1];
$z = $coords[2];
// New way - Destructuring!
[$x, $y, $z] = $coords;
// Now: $x=10, $y=20, $z=30
Skip Items You Donβt Need
$data = ['apple', 'banana', 'cherry'];
// Skip the middle one
[$first, , $last] = $data;
// $first = 'apple', $last = 'cherry'
With Associative Arrays
$person = ['name' => 'Ali', 'age' => 25];
// Extract by key
['name' => $name, 'age' => $age] = $person;
// $name = 'Ali', $age = 25
In Loops - Super Useful!
$points = [[1, 2], [3, 4], [5, 6]];
foreach ($points as [$x, $y]) {
echo "Point: ($x, $y)\n";
}
// Point: (1, 2)
// Point: (3, 4)
// Point: (5, 6)
π Spread Operator: Spill Arrays Everywhere
Story Time: You have a bag of marbles. The spread operator lets you pour them out wherever you want!
The ... Operator
$fruits = ['apple', 'banana'];
$veggies = ['carrot', 'pea'];
// Combine arrays
$food = [...$fruits, ...$veggies];
// Result: ['apple','banana','carrot','pea']
Add Items While Spreading
$nums = [2, 3, 4];
$more = [1, ...$nums, 5];
// Result: [1, 2, 3, 4, 5]
In Function Calls
function add($a, $b, $c) {
return $a + $b + $c;
}
$values = [1, 2, 3];
echo add(...$values); // 6
Copy an Array
$original = [1, 2, 3];
$copy = [...$original];
// $copy is independent now!
graph LR A["Array 1: ππ"] --> C["Combined"] B["Array 2: π₯π½"] --> C C --> D["πππ₯π½"]
π Checking Values: isset, empty, is_null
Story Time: Before eating a cookie from the jar, you check:
- Is there a jar? (
isset) - Is the jar empty? (
empty) - Is it literally nothing? (
is_null)
isset() - Does It Exist?
$data = ['name' => 'Ali', 'age' => null];
isset($data['name']); // true - exists!
isset($data['age']); // false - null counts as not set
isset($data['email']); // false - doesn't exist
empty() - Is It Falsy?
$a = "";
$b = 0;
$c = [];
$d = "hello";
empty($a); // true - empty string
empty($b); // true - zero
empty($c); // true - empty array
empty($d); // false - has content
is_null() - Strictly Nothing
$x = null;
$y = "";
$z = 0;
is_null($x); // true
is_null($y); // false - it's a string
is_null($z); // false - it's a number
Comparison Table
| Value | isset() |
empty() |
is_null() |
|---|---|---|---|
"hello" |
β true | β false | β false |
"" |
β true | β true | β false |
0 |
β true | β true | β false |
null |
β false | β true | β true |
[] |
β true | β true | β false |
| not defined | β false | β true | β οΈ error |
Real World Usage
// Safe access pattern
$user = ['name' => 'Ali'];
// Check before using
if (isset($user['email'])) {
sendEmail($user['email']);
} else {
echo "No email found";
}
// Null coalescing (modern way)
$email = $user['email'] ?? 'default@mail.com';
π§ͺ Putting It All Together
Hereβs a real scenario using everything we learned:
$products = [
['name' => 'Laptop', 'price' => 999, 'stock' => 5],
['name' => 'Mouse', 'price' => 25, 'stock' => 0],
['name' => 'Keyboard', 'price' => 75, 'stock' => 10],
['name' => 'Monitor', 'price' => 300, 'stock' => 3]
];
// 1. Filter: Only in-stock items
$inStock = array_filter($products, function($p) {
return !empty($p['stock']);
});
// 2. Map: Get just the prices
$prices = array_map(function($p) {
return $p['price'];
}, $inStock);
// 3. Reduce: Calculate total value
$total = array_reduce($prices, function($sum, $p) {
return $sum + $p;
}, 0);
echo "Total: quot; . $total; // $1374
π― Quick Summary
| Function | What It Does | Returns |
|---|---|---|
array_filter() |
Pick items that pass a test | Smaller array |
array_map() |
Transform each item | Same-size array |
array_reduce() |
Combine into one value | Single value |
[...$arr] |
Spread/unpack array | New array |
[$a, $b] |
Destructure array | Variables |
isset() |
Check if exists & not null | boolean |
empty() |
Check if falsy | boolean |
is_null() |
Check if strictly null | boolean |
π You Did It!
You now have 6 superpowers for working with PHP arrays:
- Filter - Pick only what you need
- Map - Transform everything
- Reduce - Squash into one value
- Destructure - Unpack with style
- Spread - Pour arrays anywhere
- Check - Know what youβre dealing with
Practice these, and youβll write cleaner, faster, more elegant PHP code! π
