简体   繁体   中英

How to sort an array in ascending order from Key in PHP?

I have the following array:

$arr = array('XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

Now, using a function, I generate the following array based on the previous one. When doing a print_r($new_arr) and echoing it in pre tags, this is the output:

Array
(
    [4] => l
    [3] => m
    [2] => s
    [5] => xl
    [1] => xs
)

However, I'm trying to achieve this:

Array
(
    [1] => xs
    [2] => s
    [3] => m
    [4] => l
    [5] => xl
)

Now, I did some searching on SO and found about the ksort function. Further reading in the PHP Docs, shows that this is the one to be used but when I use ksort as follows and the echoing the output, I get the value 1 only, instead of an array of values as I expected to get in the previous paragraph above:

$sorted_arr = ksort($new_arr);

On echoing $sorted_arr in pre tags, this is the output(it's just the number one):

1

I'm not really sure what is wrong here. Thanks in advance.

ksort returns a boolean value not the sorted array. Output the $new_arr variable instead.

If you go through the documentation here . You will find out ksort returns TRUE on success or FALSE on failure. Print the $new_arr instead, it was passed as reference to ksort() .

What you're looking for is the krsort function.

Note that the function sorts the input array in place, rather than returning a sorted version. The return value is a bool and just indicates success or failure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM