PHP: Array Advanced & Sorting
In the last lesson, you learned what arrays are and how to create and traverse them. This lesson unlocks where PHP arrays truly shine — the wealth of array functions that let you write stunningly concise code.
1. Merging Arrays
PHP
<?php
$arr1 = ["a" => "apple", "b" => "banana"];
$arr2 = ["b" => "blueberry", "c" => "cherry"];
// array_merge: merge — same-name string keys: latter overwrites former
$merged = array_merge($arr1, $arr2);
// ["a" => "apple", "b" => "blueberry", "c" => "cherry"]
// + operator: merge — same-name keys: former takes priority (keeps left side)
$union = $arr1 + $arr2;
// ["a" => "apple", "b" => "banana", "c" => "cherry"]
// Note: "b" kept "banana" from the left side
// array_merge re-indexes numeric arrays
$nums1 = [1, 2, 3];
$nums2 = [4, 5];
print_r(array_merge($nums1, $nums2)); // [1,2,3,4,5] (re-indexed)
print_r($nums1 + $nums2); // [1,2,3] (+ doesn't re-index)
?>
array_merge |
+ Operator |
|
|---|---|---|
| Same string keys | Latter overwrites former | Former overwrites latter |
| Indexed arrays | Re-indexes | Doesn't re-index; ignores existing indices |
💡 Tip: To merge user-submitted data with default configuration, use
$config = array_merge($defaults, $userInput); — the user's values override the defaults.
2. Array Difference and Intersection
PHP
<?php
$a = [1, 2, 3, 4, 5];
$b = [4, 5, 6, 7];
// array_diff: values in $a but not in $b
print_r(array_diff($a, $b)); // [1, 2, 3]
// array_intersect: values in both $a and $b
print_r(array_intersect($a, $b)); // [4, 5]
?>
3. Key and Value Operations
PHP
<?php
$user = ["name" => "John", "age" => 25, "city" => "New York"];
// array_keys: get all keys
print_r(array_keys($user));
// ["name", "age", "city"]
// array_values: get all values (reset to indexed array)
print_r(array_values($user));
// ["John", 25, "New York"]
// Check key or value
var_dump(array_key_exists("age", $user)); // bool(true)
var_dump(in_array("Chicago", $user)); // bool(false)
// array_search: find the key for a given value
$key = array_search(25, $user);
echo $key; // "age"
?>
4. array_filter — Filtering Arrays
Keep elements based on whether a callback returns true or false:
PHP
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Keep only even numbers
$even = array_filter($numbers, function($n) {
return $n % 2 == 0;
});
print_r($even); // [1=>2, 3=>4, 5=>6, 7=>8, 9=>10]
// Note: the keys are preserved! Use array_values to reset them:
print_r(array_values($even)); // [2, 4, 6, 8, 10]
// No callback: filters out values that equal false
$mixed = [0, "hello", "", null, false, "world", []];
$filtered = array_filter($mixed);
print_r($filtered); // [1=>"hello", 5=>"world"]
?>
▶ Example: Filtering Empty Form Data
Output:
TEXT
📖 Display only
value
PHP
<?php
// Clean up a user-submitted form (remove empty fields)
$form = [
"name" => "John",
"email" => "",
"phone" => null,
"city" => "New York",
"comment" => false
];
$cleaned = array_filter($form, function($val) {
return $val !== "" && $val !== null && $val !== false;
});
print_r($cleaned);
// ["name"=>"John", "city"=>"New York"]
?>
Output:
TEXT
📖 Display only
value
value
value
5. array_map — Applying a Function to Every Element
PHP
<?php
$numbers = [1, 2, 3, 4, 5];
// Multiply every number by 2
$doubled = array_map(function($n) {
return $n * 2;
}, $numbers);
print_r($doubled); // [2, 4, 6, 8, 10]
// With an arrow function
$squares = array_map(fn($n) => $n * $n, $numbers);
print_r($squares); // [1, 4, 9, 16, 25]
// Process multiple arrays simultaneously
$a = [1, 2, 3];
$b = [4, 5, 6];
$sums = array_map(fn($x, $y) => $x + $y, $a, $b);
print_r($sums); // [5, 7, 9]
?>
6. The Complete Sorting Family
PHP has 11 sorting functions, but you only need to remember 4 pairs + 1 custom:
PHP
<?php
$fruits = ["orange", "apple", "banana"];
$ages = ["Peter" => 32, "John" => 28, "Jane" => 35];
// === Sort by Value ===
sort($fruits); // Ascending, re-indexes → ["apple","banana","orange"]
rsort($fruits); // Descending, re-indexes → ["orange","banana","apple"]
// === Sort by Value, Preserve Keys ===
asort($ages); // Values ascending, preserve keys → ["John"=>28,"Peter"=>32,"Jane"=>35]
arsort($ages); // Values descending, preserve keys → ["Jane"=>35,"Peter"=>32,"John"=>28]
// === Sort by Key ===
ksort($ages); // Keys ascending → ["Jane"=>35,"John"=>28,"Peter"=>32]
krsort($ages); // Keys descending → ["Peter"=>32,"John"=>28,"Jane"=>35]
// === Custom Sort ===
usort($fruits, fn($a, $b) => strlen($a) <=> strlen($b));
// Sort by string length ascending
?>
| Function | Sorts By | Direction | Preserves Keys? |
|---|---|---|---|
sort |
Value | Ascending | ❌ Re-indexes |
rsort |
Value | Descending | ❌ |
asort |
Value | Ascending | ✅ |
arsort |
Value | Descending | ✅ |
ksort |
Key | Ascending | ✅ |
krsort |
Key | Descending | ✅ |
usort |
Custom | Custom | ❌ |
uasort |
Custom (value) | Custom | ✅ |
💡 Tip:
asort / ksort preserve key-value relationships — use them for associative arrays (e.g., grade sheets). sort / rsort re-index — use them for plain lists.
7. Multi-Dimensional Arrays
Arrays within arrays — typically used to store structured data:
PHP
<?php
$students = [
["name" => "Alice", "score" => 92, "city" => "New York"],
["name" => "Bob", "score" => 85, "city" => "Chicago"],
["name" => "Charlie", "score" => 78, "city" => "New York"],
];
// Access: outer first, then inner
echo $students[0]["name"]; // Alice
// Traverse
foreach ($students as $s) {
echo "{$s['name']}: {$s['score']} points<br>";
}
// Extract a single column with array_column
$names = array_column($students, "name");
print_r($names); // ["Alice", "Bob", "Charlie"]
$scores = array_column($students, "score", "name");
// ["Alice"=>92, "Bob"=>85, "Charlie"=>78]
// The third argument specifies which column to use as keys
?>
▶ Example: Sorting Multi-Dimensional Arrays
Output:
TEXT
📖 Display only
{value['name']}: \${value['price']}<br>
PHP
<?php
$products = [
["name" => "Keyboard", "price" => 299],
["name" => "Mouse", "price" => 149],
["name" => "Monitor", "price" => 1299],
["name" => "Mousepad", "price" => 29],
];
// Sort by price low to high (custom comparison function)
usort($products, fn($a, $b) => $a["price"] <=> $b["price"]);
foreach ($products as $p) {
echo "{$p['name']}: \${$p['price']}<br>";
}
// Mousepad: $29
// Mouse: $149
// Keyboard: $299
// Monitor: $1299
?>
Output:
TEXT
📖 Display only
Output displayed
The <=> spaceship operator is a perfect fit here — one line sorts a multi-dimensional array. Pure elegance.
8. Array Destructuring (PHP 7.1+)
Use [] or list() to unpack array values into multiple variables in one shot:
PHP
<?php
// Destructure an indexed array
$info = ["John", 25, "New York"];
[$name, $age, $city] = $info;
echo $name; // John
// Destructure an associative array (PHP 7.1+)
$user = ["name" => "Jane", "age" => 22];
["name" => $n, "age" => $a] = $user;
echo $n; // Jane
// Selective extraction (PHP 7.1+)
[2 => $city, 0 => $name] = $info;
echo $city; // New York
?>
▶ Example: Chaining array_map, array_filter, and array_reduce
Output:
TEXT
📖 Display only
Alice, Bob, Charlie<br>
Total revenue: \${99.99}
PHP
<?php
$orders = [120, 45, 0, 85, 0, 200, 30];
$total = array_reduce(
array_filter($orders, fn($o) => $o > 0),
fn($sum, $o) => $sum + $o,
0
);
$labels = array_map(fn($o) => $o > 0 ? "\${$o}" : "Free", $orders);
echo implode(", ", $labels) . "<br>";
echo "Total revenue: \${$total}";
Output:
TEXT
📖 Display only
Output displayed
❓ FAQ
Q How do I choose between
array_merge and the + operator?A Use
array_merge in most cases. For merging user config over defaults: $config = array_merge($defaults, $userConfig); — user settings override defaults. Only use + when you specifically need "keep existing keys and ignore duplicates."Q usort is powerful — when should I actually use it?
A When you need custom sorting rules — e.g., sort by price, sort by name length, sort by a deeply nested attribute.
usort + <=> are a golden pair.Q My multi-dimensional array is getting too deep — what should I do?
A Beyond 3 levels of nesting, consider using objects or classes to organize your data instead. Arrays are great for simple structures; objects are clearer for complex ones.
📖 Summary
array_mergemerges arrays (latter overwrites);+merges (former takes priority)array_filterfilters by condition;array_maptransforms every elementarray_keys/array_valuesextract keys or values;in_arraychecks valuessort/asort/ksortand 3 more cover most sorting needsusort+<=>for custom sorting — a multi-dimensional array sorting powerhousearray_columnextracts a specific column from multi-dimensional arrays- Array destructuring
[$a, $b] = $arrfor concise assignment
📝 Exercises
- Given two arrays of user tags, use
array_mergeto combine them andarray_uniqueto deduplicate the result. (Hint:array_unique()removes duplicates.) - From a scores array
[85, 92, 78, 95, 60]: usearray_filterto keep only passing scores (≥ 60), then usearray_mapto add 5 bonus points to each, and finally sort and output the result. - Create a multi-dimensional array with at least 5 books (title, author, price), use
usortto sort by price low to high, then usearray_columnto extract all author names.