0

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!

5
  • 2
    Why not just assign your $chk variable outside the loop? Commented Feb 19, 2019 at 15:57
  • @ChinLeung it resolves the issue? Commented Feb 19, 2019 at 15:58
  • 2
    I don't know what your issue is. But if you only want to assign $chk on first iteration, then do it before the loop. Commented Feb 19, 2019 at 15:59
  • @ChinLeung $chk returns 1 or 2, if 1 then add class only for first iteration otherwise for all iteration. this is i want. Commented Feb 19, 2019 at 16:05
  • I think you better provide expected output if $chk = 1 and $chk = 2 Commented Feb 19, 2019 at 16:28

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

9 Comments

$chk returns 1 or 2, if 1 then add class only for first iteration otherwise for all iteration. this is i want.
If that's simply what you want then the above does it. Just add your closing }.
You mean this class? <td class="tg-031e text-right availablepopup"></td>
I have to add one more class depends on this: $chk returns 1 or 2, if 1 then add class only for first iteration otherwise for all iteration.
So I'll update the above to show a certain class if iteration is the first iteration (which would be 0 not 1, since $i starts at 0 in your code.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.