Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort php array by index

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?

like image 305
woutr_be Avatar asked Oct 28 '11 06:10

woutr_be


People also ask

How to sort array elements in PHP?

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.

How to sort indexed arrays in ascending 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).

How to sort an array in Python in alphabetical order?

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:

What is relative order in array in PHP?

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.


Video Answer


1 Answers

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.

like image 90
alex Avatar answered Oct 20 '22 23:10

alex