I'm having some difficulties 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 on Index. I used ksort()
but it doesn't work, it leaves an output 1.
ksort()
doesn't return the sorted array, but rather it sorts the array in place. After calling ksort($array)
, the 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():
";
print_r($array);
if (ksort($array)) {
echo "ksort() completed successfully.
";
}
echo "After ksort():
";
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 shouldn't check the return value of ksort()
though, since ksort()
can only fail in situations in which it doesn't even get to return a failure. Therefore, the function will either return true
or the script will die, in which case the return value is irrelevant (it will always be true
).
Sort uses pass-by-reference for the array, and the return value is a boolean success or failure. I assume you're doing
$myArray = ksort($myArray);
change to
$sorted = ksort($myArray);
if (!$sorted) {
echo 'Failed to sort';
}
Use like
ksort($array);
After that print
print_r($array);
If you have used
print_r(ksort($array));
then it will return 1 if array is sorted