Sort an array by index variable

I'm having difficulty sorting a simple array that looks like this:

Array ( [3] => Array ( [0] => EU West (Ireland) [1] => eu-west-1 ) [7] => Array ( [0] => South America (Sao paulo) [1] => sa-east-1 ) [0] => Array ( [0] => US East (Virginia) [1] => us-east-1 ) [4] => Array ( [0] => Asia Pasific (Tokyo) [1] => ap-northeast-1 ) [2] => Array ( [0] => US West (Oregon) [1] => us-west-2 ) [1] => Array ( [0] => US West (N. California) [1] => us-west-1 ) [5] => Array ( [0] => Asia Pasific (Singapore) [1] => ap-southeast-1 ) [6] => Array ( [0] => Asia Pasific (Sydney) [1] => ap-southeast-2 ) ) 

I want to sort this array by index. I used ksort() , but it does not work, it leaves output 1.

+4
source share
3 answers

ksort() does not return a sorted array, but rather sorts the array in place. After calling ksort($array) contents of $array will be sorted. The function returns whether the sort was successful or not.

Example:

 $array = array(1 => 1, 20 => 1, 5 => 1); echo "Before ksort():\n"; print_r($array); if (ksort($array)) { echo "ksort() completed successfully.\n"; } echo "After ksort():\n"; print_r($array); 

The above prints:

 Before ksort(): Array ( [1] => 1 [20] => 1 [5] => 1 ) ksort() completed successfully. After ksort(): Array ( [1] => 1 [5] => 1 [20] => 1 ) 

You should not check the return value of ksort() , though, since ksort() can only fail if it cannot even fail. Therefore, the function will either return true or the script will die, in which case the return value does not matter (it will always be true ).

+6
source

Sorting uses a pass-by-reference for the array, and the return value is a logical success or failure. I guess what you do

 $myArray = ksort($myArray); 

change to

 $sorted = ksort($myArray); if (!$sorted) { echo 'Failed to sort'; } 
+1
source

Use as

 ksort($array); 

After that print

 print_r($array); 

If you used

 print_r(ksort($array)); 

then it will return 1 if the array is sorted

0
source

Source: https://habr.com/ru/post/1446915/


All Articles