PHP Tutorial · Functions and Arrays · Lesson 19 of 38
PHP Array Functions
Sort, search, filter, map and reduce arrays.
Sorting
| Function | Sorts by | Keeps keys? |
|---|---|---|
sort / rsort |
value asc / desc | no |
asort / arsort |
value asc / desc | yes |
ksort / krsort |
key asc / desc | yes |
usort |
your compare function | no |
Sorting functions change the array in place and return true.
<?php
$scores = ["ada" => 92, "lin" => 78, "sam" => 85];
arsort($scores);
print_r($scores);
$people = [["name" => "Zoe", "age" => 30], ["name" => "Al", "age" => 25]];
usort($people, fn($a, $b) => $a["age"] <=> $b["age"]);
echo implode(", ", array_column($people, "name")), "\n";
Output
Array
(
[ada] => 92
[sam] => 85
[lin] => 78
)
Al, ZoeSearching
<?php
$langs = ["php", "go", "rust"];
var_dump(in_array("go", $langs));
var_dump(array_search("rust", $langs));
var_dump(array_search("java", $langs));
Output
bool(true) int(2) bool(false)
map, filter, reduce
<?php
$nums = [1, 2, 3, 4, 5, 6];
$squares = array_map(fn($n) => $n * $n, $nums);
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
$sum = array_reduce($nums, fn($carry, $n) => $carry + $n, 0);
echo implode(" ", $squares), "\n";
print_r($evens); // keys are preserved!
print_r(array_values($evens));
echo $sum, "\n";
Output
1 4 9 16 25 36
Array
(
[1] => 2
[3] => 4
[5] => 6
)
Array
(
[0] => 2
[1] => 4
[2] => 6
)
21Other everyday helpers
array_keys, array_values, array_merge, array_slice, array_unique, array_column, array_combine, range, implode and explode:
<?php
$csv = "red,green,blue,green";
$colors = explode(",", $csv);
print_r(array_unique($colors));
echo implode(" | ", array_slice($colors, 1, 2)), "\n";
print_r(array_merge(["a" => 1], ["b" => 2, "a" => 3]));
echo implode(",", range(1, 10, 3)), "\n";
Output
Array
(
[0] => red
[1] => green
[2] => blue
)
green | blue
Array
(
[a] => 3
[b] => 2
)
1,4,7,10Test yourself
Which function sorts an associative array by value and keeps the keys?
sort()asort()ksort()usort()
Show answer
Answer: asort()
Practice next
- Two Sum · coding problem
- Leaderboard Sorting with usort and <=> · coding problem