Sorting Array Values in PHP

WBOY
Release: 2016-06-23 14:34:24
Original
882 people have browsed it

There may be times when you want to sort the values inside of an array. For example, suppose your array values are not in alphabetical order. Like this one:

$full_name = array();$full_name["Roger"] = "Waters";$full_name["Richard"] = "Wright";$full_name["Nick"] = "Mason";$full_name["David"] = "Gilmour";
Copy after login

To sort this array, you just use the assort( ) function. This involves nothing more complex than typing the word asort, followed by round brackets. In between the round brackets, type in the name of your Associative array:

asort($full_name);
Copy after login

The letter "a" tells PHP that the array is an Associative one. (If you don't have the "a" before "sort", your key names will turn in to numbers!). The "a" also tells PHP to sort by the Value, and NOT by the key. In our script above, the surnames will be sorted. If you want to sort using the Key, then you can use ksort() instead.

If you have a Scalar array (numbers as Keys), then you leave the "a" off. Like this:

$numbers = array( );$numbers[]="2";$numbers[]="8";$numbers[]="10";$numbers[]="6";sort($numbers);print $numbers[0] ;print $numbers[1];print $numbers[2] ;print $numbers[3];
Copy after login

The numbers are then sorted from lowest to highest. If you want to sort in reverse order then you need the following:

rsort( ) ? Sorts a Scalar array in reverse order
arsort( ) - Sorts the Values in an Associative array in reverse order
krsort( ) - Sorts the Keys in an Associative array in reverse order

In the next part, we look at how to get a random value from an array.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template