Elmo
Elmo

Reputation: 6471

Optimizing foreach statement

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?

Upvotes: 0

Views: 118

Answers (1)

Colin M
Colin M

Reputation: 13328

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

Upvotes: 3

Related Questions