phparrayssorting

Why does print_r(arsort($array)) output 1?


I have this array

$arr = array('key1' => 1, 'key3' => 3, 'key2' => 2);

Now i want to sort the array in the descending order of value.So i tried the following

arsort($arr);
print_r($arr);

Output

Array(
    [key3] => 3
    [key2] => 2
    [key1] => 1 
)

But when i tried the following i got output as 1

print_r(arsort($arr));

Since i am doing sorting the array and then outputting in both cases why its giving me different outputs?


Solution

  • why its giving me different outputs?

    Look at the function documentation:

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

    This function sorts an array such that array indices maintain their correlation with the array elements they are associated with.

    Returns TRUE on success or FALSE on failure.

    It uses a reference to array, sorts it and then you are outputting the sorted array in the first case.

    In the second case you are outputting the result of the function - it returns TRUE, indicating that the sorting was successful.