I'm having some difficulties sorting a simple array that looks like this:
array(4) {
[32]=>
string(1) "1"
[34]=>
string(1) "2"
[35]=>
string(1) "1"
[33]=>
string(1) "0"
}
I just want to sort it by the index so it would look like this:
array(4) {
[32]=>
string(1) "1"
[33]=>
string(1) "0"
[34]=>
string(1) "2"
[35]=>
string(1) "1"
}
I tried using sort($votes);
but this seems to remove the index and my array looks like this afterwards:
array(4) {
[0]=>
string(1) "0"
[1]=>
string(1) "1"
[2]=>
string(1) "1"
[3]=>
string(1) "2"
}
So what would be the best way of sorting this array so that the index is still the same, but sorted?
You can do even more things with arrays like sorting the elements in any order you like. PHP comes with a number of built-in functions designed specifically for sorting array elements in different ways like alphabetically or numerically in ascending or descending order.
Sorting Indexed Arrays in Ascending Order. The sort() function is used for sorting the elements of the indexed array in ascending order (alphabetically for letters and numerically for numbers).
The code reveals how this function sorts the array in alphabetical order: Here's another example. This time the array holds numbers and sorts them in numerical order: rsort () sorts the array in a descending order. Let's use it in the same script we saw in the example with guitar companies. The change of function will produce a different result:
If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.
You want to use ksort()
, which sorts an array by its keys.
ksort
Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With