Tags
Asked 2 years ago
9 Jun 2021
Views 263
steave

steave posted

How can I sort arrays and data in PHP?

How can I sort arrays and data in PHP?
shyam

shyam
answered Apr 26 '23 00:00

In PHP, there are several built-in functions that you can use to sort arrays and data. Here are some examples:

sort(): This function sorts an array in ascending order based on its values. The keys are not preserved.$fruits = array("apple", "banana", "orange",

"kiwi");
sort($fruits);
print_r($fruits);
// Output: Array ( [0] => apple [1] => banana [2] => kiwi [3] => orange )

rsort(): This function sorts an array in descending order based on its values. The keys are not preserved.


$fruits = array("apple", "banana", "orange", "kiwi");
rsort($fruits);
print_r($fruits);
// Output: Array ( [0] => orange [1] => kiwi [2] => banana [3] => apple )

asort(): This function sorts an array in ascending order based on its values, preserving the keys.


$fruits = array("a" => "apple", "b" => "banana", "c" => "orange", "d" => "kiwi");

asort($fruits);
print_r($fruits);
// Output: Array ( [a] => apple [b] => banana [d] => kiwi [c] => orange )
arsort(): This function sorts an array in descending order based on its values, preserving the keys.


$fruits = array("a" => "apple", "b" => "banana", "c" => "orange", "d" => "kiwi");

arsort($fruits);
print_r($fruits);
// Output: Array ( [c] => orange [d] => kiwi [b] => banana [a] => apple )
ksort(): This function sorts an array in ascending order based on its keys, preserving the values.



$fruits = array("b" => "banana", "a" => "apple", "d" => "kiwi", "c" => "orange");
ksort($fruits);
print_r($fruits);
// Output: Array ( [a] => apple [b] => banana [c] => orange [d] => kiwi )

krsort(): This function sorts an array in descending order based on its keys, preserving the values.


$fruits = array("b" => "banana", "a" => "apple", "d" => "kiwi", "c" => "orange");
krsort($fruits);
print_r($fruits);
// Output: Array ( [d] => kiwi [c] => orange [b] => banana [a] => apple )

Note: These functions modify the original array. If you want to sort a copy of the array, use the sorted function to create a new array.
Post Answer