Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo content inside foreach only once

Tags:

php

I'm trying to echo content inside a foreach once. At the moment, when a form is filled by the user, the message is displayed for every record skipped. If there are 35 records skipped, I will get 35 messages, because of the foreach. I want to avoid this, and be able to display only one echo for the entire results page. How can I do this? I suppose I may have to do this outside the foreach, but I have no clue how to take it out of the foreach.

foreach($allcourses as $course)
{
    if(Auth::LoggedIn())
    {
       if(Auth::$userinfo->rank == 'Student')
       {
           if($course->aircraft == '1')
           {
               echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
               continue; 
           }
           if($course->aircraft == '2')
           {
               echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
               continue; 
           }
        }
    }
}
like image 906
user2442178 Avatar asked Dec 27 '22 02:12

user2442178


1 Answers

Assuming you must maintain the structure of that object, you could just have a boolean update if $course->aircraft == 1 then echo accordingly:

$found = false;
foreach($allcourses as $course)
{
    if(Auth::LoggedIn())
    {
       if(Auth::$userinfo->rank == 'Student')
       {

           if($course->aircraft == '1')
           {
               $found = true;
           }
        }
    }
}
if($found)
{
    echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
}
like image 185
Kai Qing Avatar answered Jan 05 '23 12:01

Kai Qing