Show button once in a loop, regard of total records.

3 posts by 3 authors in: Forums > CMS Builder
Last Post: January 14, 2020   (RSS)

By Mikey - January 14, 2020 - edited: January 14, 2020

I could use some help on this if anyone has suggestions.

I have a property listing feature I'm trying to build, that will display some buttons based on the availability dates of the records assigned by the date field $record['ready'] 

At present I have three property records created.

  1. Black Creek House - Available 02-12-2020
  2. Willow House - Available 03-19-2020
  3. Brook Colonial - Move-In Ready 12-05-2019

Two of the properties are Available For Sale, and one which is Move-In Ready. I need the code below to display one one instance of the button - even if there are multiple records.

The code below works, but I need some method of breaking out of the foreach loop based on if there's multiple dates getDates that are greater or lesser than the nowTime, so the end result is there are only three buttons shown on the web page... regardless of the total number of records.

I attached a snapshot, showing what I'm getting with the code below.

<?php $nowTime = time(); ?>

<?php foreach ($property_for_saleRecords as $index => $record): ?>
<?php $getDates = strtotime($record['ready']); ?>
            
        <?php if(strtotime($getDates) < $nowTime): ?>
            <article class="text-center">
                <p><a href="#" class="button">Availble For Sale</a></p>
            </article>
          <!-- Show only once, even if there are multiple available in loop -->
        <?php endif; ?>
        
        <?php if(strtotime($getDates) > $nowTime): ?>
            <article class="text-center">
                <p><a href="#" class="button">Move-In Ready</a></p>
            </article>
          <!-- Show only once, even if there are multiple available in loop -->
        <?php endif; ?>
    
<?php endforeach ?>
        
            <article class="text-center">
                <p><a href="#" class="button">Browse Floor Plan</a></p>
            </article>

Thanks,

Zick

By Toledoh - January 14, 2020

There's probably a better way, but I would add a couple of variables: $available=0 and $move = 0.

Then in each if loop, and $available++ or $move++ (depending on which loop)

Then change the if statement to be if(strtotime($getDates) < $nowTime) AND !$available. (may have to play with that a bit).

Sound end result is that the if statement only runs if it hasn't run before....

Cheers,

Tim (toledoh.com.au)