Locked lesson.
About this lesson
Exercise files
Download this lesson’s related exercise files.
Sorting Arrays.docx59 KB Sorting Arrays - Solution.docx
59.2 KB
Quick reference
Sorting Arrays
In this video we'll learn how to sort arrays and count objects in an array.
When to use
You often need to know how many items are in an array, and sometimes need to sort items in an array.
Instructions
To count the number of items in an array:
echo count($array_name);
To sort an indexed array in ascending order
sort($array_name);
To sort an indexed array in descending order
rsort($array_name);
To sort an associative array in ascending order (use a foreach loop)
asort($array_name);
To sort an associative array in descending order (use a foreach loop)
rsort($array_name);
To print out the items in an associative array, use a foreach loop:
foreach ($array_name as $y){
echo $y . "<br/>";
}
Hints & tips
- Counting the number of items in an array is useful. echo count($array_name);
- sort(); ascending
- rsort(); descending
- to print out an associative array use a foreach loop
Lesson notes are only available for subscribers.