Reputation: 9723
I want to sort the key of the following array. I use ksort(), but i don't know how to use it. Any idea?
<?php
$a = array(
'kuy' => 'kuy',
'apple' => 'apple',
'thida' => 'thida',
'vanna' => 'vanna',
'ravy' => 'ravy'
);
$b = ksort($a);
echo "<pre>";
print_r($b);
echo "</pre>";
Upvotes: 1
Views: 1014
Reputation: 43245
ksort does not return an array. It just sorts the original array, and returns bool "Returns TRUE on success or FALSE on failure. "
So your sorted array is $a, not $b. see it here : http://codepad.org/zMTFTPGf
Upvotes: 2
Reputation: 18430
If you don't want to preserve the original order of $a then use :-
ksort($a);
print_r($a);
If you want to keep $a, but also want a sorted version use:-
$b = $a;
ksort($b);
print_r($b);
As said in my comment the manual page makes it quite clear. http://www.php.net/manual/en/function.ksort.php
Upvotes: 2
Reputation: 365
You find your answer there: http://php.net/manual/de/function.ksort.php
Use it just like:
ksort($a);
then $a is sorted.
Upvotes: 2
Reputation: 1340
As Felix said look at the documentation. you can also look at the example here
Upvotes: 0
Reputation: 46637
ksort
takes its argument by reference and modifies it directly, the return value just indicates syccess or failure.
Upvotes: 1
Reputation: 47057
ksort
returns a boolean - whether the sort succeeded or not. It sorts the array in-place - where it changes the array variable rather than returns a sorted copy.
Try:
ksort($a);
print_r($a);
Upvotes: 1
Reputation: 815
ksort returns a boolean on whether it was successful or not, it doesn't return another sorted array. It changes the original array.
print_r($a);
Upvotes: 0
Reputation: 132031
ksort()
sorts the array itself and does not create a sorted copy
$a = array(
'kuy' => 'kuy',
'apple' => 'apple',
'thida' => 'thida',
'vanna' => 'vanna',
'ravy' => 'ravy'
);
ksort($a);
echo "<pre>";
print_r($a);
echo "</pre>";
Upvotes: 4
Reputation: 86406
ksort returns boolean value and sort the original array so you should print $a
instead of $b
because $b
is a boolean value returned by the ksort which is either true or false depending on the result of ksort
ksort($a);
print_r($a);
Upvotes: 1