Pathik Vejani
Pathik Vejani

Reputation: 4491

assign variable value only for first iteration in for loop

I am using for loop and have some issue. Below is the example:

<tr>
    <td class="tg-031e">3:00</td>
    <?php for ($i=0; $i < $total_staff; $i++) {
        $chk = $this->general_model->check_for_temp_color('3:00', $selected_dt);
    ?>
        <td class="tg-031e text-right availablepopup"></td>
    <?php } ?>
</tr>

Now let say, $chk value can be one of this: 1 or 2. If it is 1 then assign class only for i==1, if it is 2 then assign class where i==1 and i==2.

Hope this is clear for understanding!

Upvotes: 0

Views: 449

Answers (2)

Chin Leung
Chin Leung

Reputation: 14921

You can achieve it like this:

<tr>
    <td class="tg-031e">3:00</td>
    <?php for ($i = 0, $chk = $this->general_model->check_for_temp_color('3:00', $selected_dt); $i < $total_staff; $i++): ?>
        <td class="tg-031e text-right availablepopup <?php if (($chk == 1 && $i == 0) || ($chk == 2 && $i != 0)): echo 'your-class'; endif; ?>"></td>
    <?php endfor; ?>
</tr>

Where your-class is the class you want.

Upvotes: 1

techcyclist
techcyclist

Reputation: 396

You could just do this:

for ($i=0; $i < $total_staff; $i++) { 
     if ($i==1)
     {
         $chk = 1;
         echo '<td class="tg-031e text-right availablepopup"></td>';
     }
     else
     {
         $chk = 2;
         echo 'something else';
     }
}

I think you just want $chk to be 1 if $i=1 right? If you actually want it to be the first instance then instead it should be if ($i==0).

And of course you will need to add back the rest of your code. It was hard to get it formatted properly in this field.

Upvotes: 2

Related Questions