The following code echos my search results on to the page. I am trying to echo a message when there are no search results but can't seem to get the message to show.
What is the best way for me to check if there are no results??
Code:
<?php if(isset($search_results)) {foreach($search_results as $result): ?>
<?php if(empty($search_results)) {echo 'No results';}
else {
echo '<div class="search_result"> <b>'.$result['title'].'</b><br />';
echo '<span class="search_result_url">'.$result['link'].'</span><br />';
echo $result['text'].'<br /></div>';
} ?>
<?php endforeach; } else {echo '<b>Please type what you are looking for into the search bar and press \'enter\'</b>';}?>
You need to check whether your $search_results array is empty before the foreach loop
<?php
if( isset($search_results) ) {
if( empty($search_results) ) {
echo 'No results';
} else {
foreach($search_results as $result) {
echo '<div class="search_result"> <b>'.$result['title'].'</b><br />';
echo '<span class="search_result_url">'.$result['link'].'</span><br />';
echo $result['text'].'<br /></div>';
}
}
} else {
echo '<b>Please type what you are looking for into the search bar and press \'enter\'</b>';
}
?>
your script cannot possibly work, since the foreach loop is cast as soon as $search_results is NOT empty, thus if(empty($search_results)) {echo 'No results';} is never true.
try if(empty($result)) {echo 'No results';}
or if($result!='$empty') {echo 'No results';} ($empty depending on what 'empty' means)