Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP foreach, if statement

Tags:

php

I have a table listing several elements, and their expiration date.

I need a function that says, "If the expiration date is later than today (for each element), then don't show".

It seems pretty simple, but I'm stuck!


Edit

<?php foreach($codes->result_array() as $row):?>
<tr>
    <td><?php print $row['description']?></td>
    <td><?php print $row['credits']?></td>
    <td><?php print $row['code']?></td>
    <td><? echo date("F jS, Y", strtotime($row['exp_date']));?></td>
    <td><? echo date("F jS, Y", strtotime($row['create_date']));?></td>
    <td>
        <!-- Icons -->
         <a href="<? echo base_url()?>admin/home/editCode/<?php print $row['id']?>" title="Edit"><img src="<? echo base_url()?>assets/images/icons/pencil.png" alt="Edit" /></a>
         <a href="<? echo base_url()?>admin/home/deleteCode/<?php print $row['id']?>" title="Delete" class="delete-code"><img src="<? echo base_url()?>assets/images/icons/cross.png" alt="Delete" /></a> 
    </td>
<?php endforeach;?>
like image 555
Kevin Brown Avatar asked May 25 '26 11:05

Kevin Brown


2 Answers

This is a very basic example.

foreach($elements as $element)
{
    if(strtotime($element['expiration_date']) < now())
    {
        echo $element['expiration_date'];
    }
}
like image 84
Ikke Avatar answered May 28 '26 04:05

Ikke


Seperate your concerns will help you see your question clearer.

In your controller:

<?php
$result_array = $codes->result_array();
$results = array();
$today = time();

foreach($codes->result_array() as $row)
{
    if(strtotime($row['exp_date']) <= $today)
    {//-- Keep this
        $results[] = $row;
    }
}
?>

In your view:

<?php foreach($results as $result): ?>
<tr>
    <td><?php print $result['description']?></td>
    <td><?php print $result['credits']?></td>
    <td><?php print $result['code']?></td>
    <td><? echo date("F jS, Y", strtotime($result['exp_date']));?></td>
    <td><? echo date("F jS, Y", strtotime($result['create_date']));?></td>
    <td>
        <!-- Icons -->
         <a href="<? echo base_url()?>admin/home/editCode/<?php print $result['id']?>" title="Edit"><img src="<? echo base_url()?>assets/images/icons/pencil.png" alt="Edit" /></a>
         <a href="<? echo base_url()?>admin/home/deleteCode/<?php print $result['id']?>" title="Delete" class="delete-code"><img src="<? echo base_url()?>assets/images/icons/cross.png" alt="Delete" /></a> 
    </td>
<?php endforeach;?>
like image 40
Trav L Avatar answered May 28 '26 03:05

Trav L