php if foreach statement works, but else message not displaying
foreach, if-statement, php
Solution
You a testing if $bookmark exists! I assume that it always exists, either empty or with array of values!
Try this:
<?php
if (is_array($bookmark) && count($bookmark)>=1):
foreach($bookmark as $b): ?>
<?php if ($b->bookmark_id != 0) { ?>
<li><?php echo $bk->bookmark_name; ?></li>
<?php } ?>
<?php
endforeach;
else:
print "Your bookmark list is empty.";
endif;
?>
Read: PHP is_array() | count()
EDITED
Related to the recently posted comment "Yes, the array is returning results; I am using the second if statement to limit what is shown. It sounds like my else statement should be tied to the second if clause, instead of the first. The issue for me isn't whether there are results; it's whether after the results are filtered anything remains.":
<?php
// reset variable
$count = 0;
// if it is an array and is not empty
if (is_array($bookmark) && count($bookmark)>=1):
foreach($bookmark as $b):
if ($b->bookmark_id != 0) {
echo '<li>' . $bk->bookmark_name . '</li>';
} else {
$count++; // no data, increase
}
// check if the counter was increased
if ($count>=1) {
print "Your bookmark list is empty.";
}
endforeach;
else:
print "bookmark not found.";
endif;
?>
Problem
I'm getting an array of data from my model, and am using a php foreach statement to display it in a view. I'm adding another layer of logic to show only certain bookmark_ids. The data is displaying fine; but for some reason the "else" message (tied to the first if clause) isn't showing if no data is returned. I need to figure out how to get that message to display. ``` <?php if ($bookmark): foreach($bookmark as $b): ?> <?php if ($b->bookmark_id != 0) { ?> <li><?php echo $bk->user_id; ?> <?php echo $bk->bookmark_name; ?></li> <?php } ?> <?php endforeach; else: print "Your bookmark list is empty."; endif; ?> ```