Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Foreach , Where

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

like image 273
RIK Avatar asked Dec 06 '22 05:12

RIK


1 Answers

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.

like image 125
Socce Avatar answered Dec 21 '22 20:12

Socce