Cara Sorting Array di PHP 5, 6, 7 sangat diperlukan untuk manipulasi data baik dari database atau hasil submit user. Berikut beberapa fungsi sorting array di pemograman PHP.
- sort() - urutkan array ascending
- rsort() - urutkan arrays descending
- asort() - urutkan arrays ascending, berdasarkan value
- ksort() - urutkan arrays ascending, berdasarkan key
- arsort() - urutkan arrays descending, berdasarkan value
- krsort() - urutkan arrays descending, berdasarkan key
Untuk contoh penggunaan sorting array PHP sebegai berikut.
- sort array<?php
$cars = array("Toyota", "Honda", "Mercedes");
sort($cars);
?>Output: Honda, Mercedes, Toyota - rsort array<?php
$cars = array("Toyota", "Honda", "Mercedes");
rsort($cars);
?>Output: Toyota, Mercedes, Honda - asort array<?php
$cars = array("Toyota", "Honda", "Mercedes");
asort($cars);
?>Output: Toyota, Honda, Mercedes - ksort array<?php
$cars = array("Volvo", "BMW", "Toyota", "Wuling");
ksort($cars);
?>Output:0 - Volvo
1 - BMW
2 - Toyota
3 - Wuling - arsort array<?php
$cars = array("Volvo", "BMW", "Toyota", "Wuling");
arsort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $x.' - '.$cars[$x];
echo "<br>";
}
?>Output:0 - Volvo
1 - BMW
2 - Toyota
3 - Wuling - krsort array
<?php
$cars = array("Volvo", "BMW", "Toyota", "Wuling");
arsort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $x.' - '.$cars[$x];
echo "<br>";
}
?>Output:
Hasil diatas akan berbeda jika sobat mendefiniskan key pada sebuah array yang dibuat.0 - Volvo
1 - BMW
2 - Toyota
3 - Wuling