php · level 2 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
puts an array in order, right where it is.
sort($names) puts the items in order: numbers smallest first, words A to Z. rsort does the reverse. Both throw the old keys away and number the items from 0 again, which is fine for a plain list.
An associative array needs its keys kept. sorts by value and keeps each key with its value. arsort does the same the other way round, and ksort sorts by key instead.
They all sort : they change the array you hand them and give back only true. So never write $sorted = sort($names);. Sort first, then use $names.
<?php
$names = ["Zoe", "Ali", "Mo"];
sort($names);
echo implode(", ", $names) . "\n";
$points = ["Reds" => 12, "Blues" => 18, "Greens" => 9];
arsort($points);
foreach ($points as $team => $score) {
echo "$team: $score\n";
} Capital letters sort before small ones, so "Zebra" comes before "apple".
guess first
This one uses ksort. What will it show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$heights = ["Ivy" => 140, "Raj" => 152, "Ola" => 135];
ksort($heights);
foreach ($heights as $name => $cm) {
echo "$name: $cm cm\n";
}
your turn
Your turn. Sort your snack drawer.
Type four snacks in any order, all in small letters. Run it to see them A to Z, then Z to A.
fix it
The sorted scores never appear. Can you fix it?
- The TypeError says
implodewas giventrue, not an array. What didsorthand back on line 3? sortsorts in place and gives back onlytrue. The sorted numbers are still in$scores.- Make line 3
sort($scores);and implode$scoreson line 4, then press run.
nailed it
everything is in order now. :D
sortandrsortput a plain list in order.asort,arsortandksortkeep keys with values.- Sorting happens in place, so use the same array after.
new words in your collection
- sort
- in place
- asort
This lesson isn’t saved. A free account remembers every lesson you finish.