简体   繁体   中英

I want to execute an if else statement inside for each loop only once in PHP

My code is:

<tbody>
                <?php
            $query = "SELECT * FROM `tblcourse`";
            $mydb->setQuery($query);
            $cur = $mydb->loadResultList();
            foreach ($cur as $result)
            {?>
              <tr>
                <td align="center" width="20%">
                    <?php
                    foreach($arr as $v)
                    {
                        if ($result->COURSEID==$v) {
                            echo "<a href='index.php?q=rollout'> Roll out</a>";
                        }
                        else {
                            echo "<a href='index.php?q=enroll'> Enroll</a>";
                        }
    
                }?>

                 </td>
            </tr>
              <?php
            }
          ?>
        </tbody>

If $arr has 2 elements ($cur has 5 elements) then i want output like this :-

  • rollout
  • enroll
  • enroll
  • rollout
  • enroll

instead I'm getting :-

  • rollout enroll
  • enroll enroll
  • enroll enroll
  • enroll rollout
  • enroll enroll

It looks as though you want to output ROLL OUT if the COURSEID of $result is one of the values in arr and otherwise you want to output ENROLL.

Remove the foreach($arr as $v) loop and replace with

if (in_array($result->COURSEID,$arr)) {
  echo "<a href='index.php?q=rollout'> Roll out</a>";
} else {
  echo "<a href='index.php?q=enroll'> Enroll</a>";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM