0

This is my code:

<?php foreach ($classes as $str) foreach ($str as $class): ?>
...
<?php endforeach ?>

$str has just one string value with a random string index.

Can the first statement be optimized to reduce it to just one foreach?

asked Feb 7, 2013 at 14:31
5
  • 1
    what is the structure of $classes? Commented Feb 7, 2013 at 14:32
  • 4
    Since your $classes array appears to be 2D, you'll probably need 2 loops. Really, we need to know what is in the array, and what you plan to do in the loop. Commented Feb 7, 2013 at 14:33
  • 1
    Most importang this is what you want to do with this data. Commented Feb 7, 2013 at 14:34
  • 2
    also, and maybe i'm wrong, but it seems like you are confusing "optimize" with "do everything in the shortest amount of space possible" Commented Feb 7, 2013 at 14:34
  • 1
    Without forgetting that writing readable, understandable and possibly self-documenting code is at least as important as writing code that runs fast! Commented Feb 7, 2013 at 14:37

1 Answer 1

3

You could flatten your classes array, but it wouldn't give you any performance benefit because internally, the flattening of an array will iterate over the entire array anyway.

The short answer is: no - there's no way to optimize this without changing the way that the $classes array is constructed (if that's possible) - assuming you need access to all of the 2nd-level children of the $classes array.

Edit: If your $str sub-array only has one random child with a random array index, you could use current($str) - it might prove to be SLIGHTLY faster than a foreach

answered Feb 7, 2013 at 14:33
Sign up to request clarification or add additional context in comments.

1 Comment

as if you extracted this piece of writing from my heart :)

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.