Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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]);
}
share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
Thank you for your explanations –  n.h. Jul 13 at 20:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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