×

php · level 2 · unit 2 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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".