'sort() not affecting original array while inside foreach loop

I have array with structure:

Array
(
    [months] => Array
        (
            [01] => Array
                (
                    [0] => 16
                    [1] => 31
                )

            [02] => Array
                (
                    [0] => 16
                    [1] => 25
                    [2] => 10
                    [3] => 15
                )

        )

)

Now I trying to use uasort in loop:

        foreach ($dates['months'] as $month) {
            uasort($month, function($a, $b) {
                return $a <=> $b;
            });
        }

But it's not sorting by days (sub-array of month) - why?



Solution 1:[1]

You need to pass $month with reference in foreach loop

foreach ($dates['months'] as &$month) 

uasort() modifies arrays by reference but you modify array that is inside the other array, so months are modified but they are not saved in $dates variable.

It can be easily checked by print_r($dates['months']); after uasort() function in the loop.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1