phparraysksort

PHP - Sorting Associative Array with ksort()


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';

Solution

  • 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.