I have a foreach loop inside of an if statement. My code is in shorthand format. I do not want the foreach loop to execute if the if condition returns true and instead echo out a message ‘sorry database is empty!’
Functional Code
<?php if (!$check == 0) : ?>
<?php foreach... ?>
...
<?php endforeach; ?>
<?php endif; ?>
<?php if ($check == 0) echo 'Sorry database is empty!'; ?>
What I don’t like about this code is that I have two separate if conditions. Granted it works as it should but I would prefer to to have an else in the first if.
- What is the proper syntax for what I want to do?
Alternatively if your answer is something like this:
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true
Explain how that would stop the foreach from executing.
Just use an else:
You can also shorten this:
to just this: