Display the message in the foreach loop with if else condition

advertisements

I want to display error message if condition is false in foreach loop. Here is my code

foreach($items as $item){
    if($item['userid'] == logged_in()) {
        echo $item['title'];
    } else {
        echo 'You do not have permission to view items';
    }
}

// other code here needs to continue after loop

So with above code the error message display as many time the loop runs. So if there is 5 items than message display for 5 times. While I want to display only one time if condition is false. I have tried with break; and continue; but both stop executing further php code.

foreach($items as $item){
    if($item['userid'] == logged_in()) {
        echo $item['title'];
    } else {
        echo 'You do not have permission to view items';
        break; // or continue
    }
}

// other code here needs to continue after loop

So what can I do to display this message only one and further code also will execute?


use this-

$once=false;
foreach($items as $item){
    if($item['userid'] == logged_in()) {
        echo $item['title'];
    } else {
       $once=true;
    }
}

if($once)
   echo 'You do not have permission to view items';