2

php: alphabetically sort multi-dimensional array by its key?

I'm trying to do the exact same thing as the guy in the thread above me. But my ksort($array) seems to return a number 1. What am I doing wrong?

3
  • You need to provide some sample code if you want people to help you :-). How did you use ksort? What does your array look like? Commented Sep 2, 2011 at 7:34
  • Can you show us the array you're attempting to sort? Commented Sep 2, 2011 at 7:35
  • php.net/manual/en/array.sorting.php is a good starting point; or post code. Commented Sep 2, 2011 at 7:37

4 Answers 4

8

Have a look at the manual:

bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

You see, ksort returns a boolean value, and directly works on the given array (note the reference sign&). So what you're probably doing is assigning the return value of ksort, like:

$array = ksort($array);

instead of, just:

ksort($array);
Sign up to request clarification or add additional context in comments.

Comments

3

The function does in-place sorting, the function return TRUE on success or FALSE on failure.

Refer to example from http://php.net/manual/en/function.ksort.php

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
?>

The sorted result is in the variable $fruits, not from the function's return value.

If you try print_r($fruits), you will get the result like this

Array
(
    [a] => orange
    [b] => banana
    [c] => apple
    [d] => lemon
)

Comments

0

ksort() doesn't return an array, it manipulates the array you pass to it.

Comments

0

It doesn't literally return an 1, it returns true:

http://php.net/manual/en/function.ksort.php

Return Values

Returns TRUE on success or FALSE on failure.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.