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]);
}
asked Jul 13, 2015 at 18:15
\$\endgroup\$
0

1 Answer 1

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.

answered Jul 13, 2015 at 19:18
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.