Sorting arrays is an important task when dealing with data in PHP. You can sort numerical, string, and associative arrays using PHP’s built-in functions.
🔹 Sorting an Indexed Array
Use sort() to arrange an array in ascending order.
<?php $numbers = array(8, 3, 5, 1, 9); sort($numbers); print_r($numbers); ?>
Output: Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 8 [4] => 9 )
🔹 Sorting in Descending Order
Use rsort() to sort an array in descending order.
<?php
$letters = array("Z", "M", "A", "K");
rsort($letters);
print_r($letters);
?>
Output: Array ( [0] => Z [1] => M [2] => K [3] => A )
🔹 Sorting an Associative Array by Values
Use asort() to sort an associative array by values while keeping key-value pairs intact.
<?php
$ages = array("Alice" => 25, "Bob" => 20, "Charlie" => 30);
asort($ages);
print_r($ages);
?>
Output: Array ( [Bob] => 20 [Alice] => 25 [Charlie] => 30 )
🔹 Sorting an Associative Array by Keys
Use ksort() to sort an associative array by keys alphabetically.
<?php
$students = array("David" => 85, "Alice" => 92, "Bob" => 78);
ksort($students);
print_r($students);
?>
Output: Array ( [Alice] => 92 [Bob] => 78 [David] => 85 )
🔹 Sorting in Reverse Order
Use arsort() for values and krsort() for keys in reverse order.
<?php
$points = array("Player1" => 50, "Player2" => 80, "Player3" => 40);
arsort($points);
print_r($points);
?>
Output: Array ( [Player2] => 80 [Player1] => 50 [Player3] => 40 )
🎯 Key Takeaways
sort()– Sorts an indexed array in ascending order.rsort()– Sorts an indexed array in descending order.asort()– Sorts an associative array by values (ascending).arsort()– Sorts an associative array by values (descending).ksort()– Sorts an associative array by keys (ascending).krsort()– Sorts an associative array by keys (descending).
📝 Practice Time!
Try creating an array of your favorite pizza toppings 🍕, then use different sorting methods to arrange them by name or popularity!