Home >Backend Development >PHP Problem >How to output php array after sorting
PHP is a widely used scripting language that is ideal for handling tasks in web development. Among them, array operations in PHP are also a very powerful function. If you want to sort the elements in an array and need to output the sorted results, this article will show you how to do it.
The sort() function is the simplest sorting function in PHP, which can sort the array in ascending order. The following is an example:
$fruit = array("apple", "orange", "banana", "pear"); sort($fruit); print_r($fruit);
The above code will output:
Array ( [0] => apple [1] => banana [2] => orange [3] => pear )
rsort() function is the sort() function Working in reverse, it sorts the array in descending order. The following is an example:
$fruit = array("apple", "orange", "banana", "pear"); rsort($fruit); print_r($fruit);
The above code will output:
Array ( [0] => pear [1] => orange [2] => banana [3] => apple )
asort() function is to associate according to the value The array is sorted, and unlike the sort() function, it sorts while retaining all keys. The following is an example:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); asort($age); print_r($age);
The above code will output:
Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )
arsort() function is asort() function Working in reverse, it sorts an associative array in descending order of value. The following is an example:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); arsort($age); print_r($age);
The above code will output:
Array ( [Joe] => 43 [Ben] => 37 [Peter] => 35 )
ksort() function is to associate according to the key The array is sorted, and unlike the sort() function, it sorts while retaining all keys. The following is an example:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); ksort($age); print_r($age);
The above code will output:
Array ( [Ben] => 37 [Joe] => 43 [Peter] => 35 )
krsort() function is the ksort() function Working in reverse, it sorts an associative array in descending order by key. The following is an example:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); krsort($age); print_r($age);
The above code will output:
Array ( [Peter] => 35 [Joe] => 43 [Ben] => 37 )
Summary
This article introduces some common array sorting functions in PHP, including sort(), rsort( ), asort(), arsort(), ksort() and krsort() functions. In the actual development process, you can choose the appropriate function to sort the array as needed and output the sorted results. Hope this article is helpful to you!
The above is the detailed content of How to output php array after sorting. For more information, please follow other related articles on the PHP Chinese website!