Home > Net >  Use Empty Function with Foreach loop
Use Empty Function with Foreach loop

Time:12-02

I want to output a message when there are no items in the database. The code does not print the statement when the database doesn't have data.

This is my code,
<?php foreach($latest_tenders as $tenders):
if(!empty($tenders)){ 
$time = strtotime($tenders['post_date']);
                      $month=date('m', $time);
                                switch($month){
                                   case 1:
                                    echo "January "; break;
                                      .
                                      .
                                      .
                                    case 12:
                                     echo "December "; break;
                                   default:
                                    echo "January ";
                            }
echo date('d', $time).', ';
echo date('Y', $time).'&nbsp';
echo date('h', $time).':'; echo date('i',     $time).' |&nbsp';?>
     <i ></i> <?php echo $tenders['author'];?></p> 
       </div><br/>
     <?php 
         }
            else{?>
      <p style=" font-size:13px; word-spacing: 5px;color:tomato;">
          Tender Name: No advertised Tenders, Check again later.
      </p>
        <?php
            }
            endforeach;
            ?>

CodePudding user response:

Assuming $latest_tenders is your database result, first check if the $latest_tenders array is not empty. If it's not empty: loop over $latest_tenders and print its $tenders. Else (it is empty): print your error message.

<?php if(!empty($latest_tenders)) : ?>
    <?php foreach($latest_tenders as $tenders):
        $time = strtotime($tenders['post_date']);
        $month=date('m', $time);
        switch($month){
            case 1:
                echo "January "; break;
                    .
                    .
                    .
            default:
                echo "January ";
        }
        echo date('d', $time).', ';
        echo date('Y', $time).'&nbsp';
        echo date('h', $time).':';
        echo date('i',     $time).' |&nbsp';
    ?>
        <i ></i> <?php echo $tenders['author'];?></p></div><br/>
    <?php endforeach; ?>
<?php else : ?>
    <p style=" font-size:13px; word-spacing: 5px;color:tomato;">
        Tender Name : No advertised Tenders for No, Check again later.
    </p>
<?php endif; ?> 
  • Related