Is there a way of adding a where class to a foreach equation in PHP.
At the moment I am adding an if to the foreach like this.
<?php foreach($themes as $theme){
if($theme['section'] == 'headcontent'){
//Something
}
}?>
<?php foreach($themes as $theme){
if($theme['section'] == 'main content'){
//Something
}
}?>
Presumably the PHP has to loop through all results for each of these. Is there are more efficient way of doing this. Something like
foreach($themes as $theme where $theme['section'] == 'headcontent')
Can this be done
A "foreach-where" would be exactly the same as a "foreach-if", because anyway PHP has to loop through all items to check for the condition.
You can write it on one line to reflect the "where" spirit:
foreach ($themes as $theme) if ($theme['section'] == 'headcontent') {
// Something
}
This becomes really the same as the construct suggested at the end of the question; you can read/understand it the same way.
It does not, however, address the fact that in the question's specific scenario, using any kind of "foreach-where" construction would in effect loop through all items several times. The answer to that lies in regrouping all the tests and corresponding treatments into a single loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With