Sandeep Belchandan
Sandeep Belchandan

Reputation: 3

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 :-

instead I'm getting :-

Upvotes: 0

Views: 262

Answers (1)

A Haworth
A Haworth

Reputation: 36512

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>";
}

Upvotes: 1

Related Questions