PHP & MySQL Tutorial
- Arrays III (Sort)
bogotobogo.com site search:
Arrays III - Sorting Array Elements
bogotobogo.com site search:
PHP provides functions to sort array elements.
- Ascending(1->9 or a->z)
- sort() - sorts by value discarding the original key
- asort() - sorts by value keeping the original key
- ksort() - sorts by key
- Descending(9->1 or z->a)
- rsort() - sorts by value discarding the original key
- arsort() - sorts by value keeping the original key
- krsort() - sorts by key
sort() and rsort()
<?php $numbers = array('tres'=>3, 'uno'=>1, 'quatro'=>4, 'dos'=>2); echo 'Initial elements: '; foreach($numbers as $n) { echo "$n" . " "; } echo "\n\n"; echo 'ascending sort: '; sort($numbers); foreach($numbers as $n) { echo "$n" . " "; } echo "\n"; echo 'descending sort: '; rsort($numbers); foreach($numbers as $n) { echo "$n" . " "; } ?>
Output:
Initial elements: 3 1 4 2 ascending sort: 1 2 3 4 descending sort: 4 3 2 1
Note that the key will be discarded by the sort() and rsort() functions. Therefore, these functions should not be used where the keys are important. In that case, we should use the asort() or arsort() instead.
asort() and arsort()
<?php $numbers = array('tres'=>3, 'uno'=>1, 'quatro'=>4, 'dos'=>2); echo 'Initial elements: '; foreach($numbers as $key=>$value) { echo "$key" . "=>" . "$value" . " " ; } echo "\n\n"; echo 'ascending sort by value: '; asort($numbers); foreach($numbers as $key=>$value) { echo "$key" . "=>" . "$value" . " " ; } echo "\n"; echo 'descending sort by value: '; arsort($numbers); foreach($numbers as $key=>$value) { echo "$key" . "=>" . "$value" . " " ; } ?>
Output:
Initial elements: tres=>3 uno=>1 quatro=>4 dos=>2 ascending sort by value: uno=>1 dos=>2 tres=>3 quatro=>4 descending sort by value: quatro=>4 tres=>3 dos=>2 uno=>1
ksort() and krsort()
<?php $numbers = array('tres'=>3, 'uno'=>1, 'quatro'=>4, 'dos'=>2); echo 'Initial elements: '; foreach($numbers as $key=>$value) { echo "$key" . "=>" . "$value" . " " ; } echo "\n\n"; echo 'ascending sort by key: '; ksort($numbers); foreach($numbers as $key=>$value) { echo "$key" . "=>" . "$value" . " " ; } echo "\n"; echo 'descending sort by key: '; krsort($numbers); foreach($numbers as $key=>$value) { echo "$key" . "=>" . "$value" . " " ; } ?>
Output:
Initial elements: tres=>3 uno=>1 quatro=>4 dos=>2 ascending sort by key: dos=>2 quatro=>4 tres=>3 uno=>1 descending sort by key: uno=>1 tres=>3 quatro=>4 dos=>2
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization