PHP Sorting and Array Functions
ExamplePHP
<?php
$nums = [5, 2, 9, 1];
sort($nums);
echo implode(",", $nums), "\n";
rsort($nums);
echo implode(",", $nums), "\n";
$ages = ["Sam" => 22, "Ada" => 36, "Lee" => 41];
asort($ages); // by value
echo json_encode($ages), "\n";
ksort($ages); // by key
echo json_encode($ages), "\n";
arsort($ages);
echo json_encode($ages), "\n";
$people = [["n" => "Ada", "age" => 36], ["n" => "Sam", "age" => 22]];
usort($people, fn($a, $b) => $a["age"] <=> $b["age"]);
echo $people[0]["n"], "\n";
echo json_encode(array_unique([1, 2, 2, 3, 1])), "\n";
echo json_encode(array_slice([10, 20, 30, 40], 1, 2)), "\n";
echo json_encode(array_merge([1, 2], [3])), "\n";
echo json_encode(array_reverse([1, 2, 3])), "\n";
echo json_encode(array_combine(["a", "b"], [1, 2])), "\n";
echo json_encode(array_column($people, "n")), "\n";Output
1,2,5,9
9,5,2,1
{"Sam":22,"Ada":36,"Lee":41}
{"Ada":36,"Lee":41,"Sam":22}
{"Lee":41,"Ada":36,"Sam":22}
Sam
{"0":1,"1":2,"3":3}
[20,30]
[1,2,3]
[3,2,1]
{"a":1,"b":2}
["Sam","Ada"]usort takes your own comparison function, using the spaceship operator <=> that returns -1, 0 or 1.
Quick check
Which function sorts an array with your own comparison function?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.