2
\$\begingroup\$

I am using a foreach loop to sort an associative array alphabetically. I would like to know if there is a more proper and/or efficient way of doing it.

The array:

Array
(
    [gr_c] => Array
        (
            [f] => 'value...'
            [a] => 'value...'
            [d] => 'value...'
            [m] => 'value...'
            [c] => 'value...'
            [t] => 'value...'
        )

    [gr_a] => Array
        (
            [h] => 'value...'
            [e] => 'value...'
            [m] => 'value...'
            [a] => 'value...'
            [o] => 'value...'
            [i] => 'value...'
            [c] => 'value...'
            [t] => 'value...'
            [b] => 'value...'
        )

    [gr_b] => Array
        (
            [h] => 'value...'
            [d] => 'value...'
        )
)

became:

Array
(
    [gr_c] => Array
        (
            [a] => 'value...'
            [c] => 'value...'
            [d] => 'value...'
            [f] => 'value...'
            [m] => 'value...'
            [t] => 'value...'
        )

    [gr_a] => Array
        (
            [a] => 'value...'
            [b] => 'value...'
            [c] => 'value...'
            [e] => 'value...'
            [h] => 'value...'
            [i] => 'value...'
            [m] => 'value...'
            [o] => 'value...'
            [t] => 'value...'
        )

    [gr_b] => Array
        (
            [d] => 'value...'
            [h] => 'value...'
        )
)

used snippet:

foreach ($array_name as $key => $value) {
    ksort($array_name[$key]);
}
\$\endgroup\$
3
\$\begingroup\$

That snippet of 3 lines you used, is fine as it is, nothing really wrong with it. It's proper, efficient, natural, easy to understand.

There is just one thing I'd pick on, is that the $value variable in the foreach expression is not used. Another way to achieve the same thing without unused variables is to use & to pass the loop variable by reference:

foreach ($array_name as &$arr) {
    ksort($arr);
}

This has the advantage that the loop index variable $key is now gone too, we're working with the data that really matters, which is the $arr to sort.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.