0
<? foreach ($cases as $case) :?>
<? if (isset($case['case_status']) && ($case['case_status'] == 'Incomplete')) :?>
<div>
    <div class="alert alert-error">    
        <?= $warning ?>
    </div>

I'm trying to have that foreach print out the div only once if the condition is met. The problem is, for every case that meets the condition the div is printed.

I have tried using in_array, but I don't think I understand the syntax. Is in_array correct? Is there a better way to do this?

2
  • Variables are free. Use one to remember if you have already printed the warning. Commented Aug 12, 2013 at 22:49
  • 2
    Add <?php break; ?> at the end of (but inside) the if to stop the foreach. Commented Aug 12, 2013 at 22:53

2 Answers 2

1

You can use a flag to mark, that you have already printed the div and add an extra condition to if:

<? 
$flag = false;
foreach ($cases as $case) :?>
<? if (isset($case['case_status']) 
       && ($case['case_status'] == 'Incomplete')
       && ($flag == false)) :?>
<div>
    <div class="alert alert-error">    
        <?= $warning ?>
    </div>
    <?php $flag = true; ?>

Or if you don't need to do anything in that loop, you can just break it after the first encountered element.

<? 
foreach ($cases as $case) :?>
<? if (isset($case['case_status']) && ($case['case_status'] == 'Incomplete')) :?>
<div>
    <div class="alert alert-error">    
        <?= $warning ?>
    </div>
    <?php break; ?>
Sign up to request clarification or add additional context in comments.

4 Comments

won't this prevent further legitimate errors from printing once the flag has been set to true?
@Maximus2012 The PO said, that he doesn't want to print this block. The flag will do it. The other conditions will stay unmodified. If he doesn't use this foreach for anything else, except for finding, if the element is present in the array, break will the best solution.
@Maximus2012: that is what is asked: "I'm trying to have that foreach print out the div only once if the condition is met."
oh...ok. Thanks for the clarification. I guess I missed that part of the original question.
1
<?php
  $printed = array();
  foreach ($cases as $case) :?>
<? if (!in_array( $case['case_status'] ) && isset($case['case_status']) && ($case['case_status'] == 'Incomplete')) : ?>
<div>
    <div class="alert alert-error">    
        <?= $warning ?>
    </div>
<?php
    $printed[] = $case['case_status'];
  endif;
?>

This way you are saving every printed case_status and comparing it with in_array.

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.