PHP - Sorting Associative Array with ksort()

270 Views Asked by At

I am trying to sort an associative array according to the key

$fruit[2999] = 'apple';
$fruit[332] = 'banana';
$fruit[400] = 'pineapple';
$fruit[87] = 'pear';

$fruit = ksort($fruit);

print_r($fruit);

But the output is

1

How can I sort the array so that the array will be in this order:

$fruit[87] = 'pear';
$fruit[332] = 'banana';
$fruit[400] = 'pineapple';
$fruit[2999] = 'apple';
2

There are 2 best solutions below

1
rawathemant On BEST ANSWER

Don't put array sort result into array variable

$fruit[2999] = 'apple';
$fruit[332] = 'banana';
$fruit[400] = 'pineapple';
$fruit[87] = 'pear';

ksort($fruit);

print_r($fruit);

You got out 1 because ksort return true/false. and you print this value.

0
Péter Kádár On

According to the officaial PHP manual (http://php.net/manual/en/function.ksort.php), the ksort() function returns true/false, on success/error. So the correct answer is:

$fruit[2999] = 'apple';
$fruit[332] = 'banana';
$fruit[400] = 'pineapple';
$fruit[87] = 'pear';

ksort($fruit);

print_r($fruit);