string(1) "...">

Sort php array by index

I'm having difficulty 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 index so that it looks 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:

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 to sort this array so that the index is all the same but sorted?

+7
source share
4 answers

You want to use one that sorts the array by key. ksort()

ksort

Sorts the array by key, keeping the key to data correlation. This is mainly useful for associative arrays.

+13
source

PHP . PHP.

+1

ksort($votes);

array(4) {
  [32]=>
  string(1) "1"
  [33]=>
  string(1) "0"
  [34]=>
  string(1) "2"
  [35]=>
  string(1) "1"
}

Read more ... this

0
source

https://www.php.net/manual/en/function.asort.php

It looks like you are looking.

this will sort the array and preserve existing indexes

array(4) {
  [33]=>
  string(1) "0"
  [32]=>
  string(1) "1"
  [35]=>
  string(1) "1"
  [34]=>
  string(1) "2"
}
0
source

All Articles