PHP Foreach , Where

15,091

Solution 1

Use a SWITCH Statement.

 <?php
    foreach($themes as $theme)
      {
        switch($theme['section'])
        {
            case 'headcontent':
                //do something
                break;
            case 'main content':
                //do something
                break;
        }
       }
    ?>

Solution 2

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.

Share:
15,091
RIK
Author by

RIK

Updated on June 23, 2022

Comments

  • RIK
    RIK almost 2 years

    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