Display a foreach item only once (if this item is within the if condition)

0

Hello! For a chat, I want to display the message date only once, this being; in the first message only. Example:

ONTEM Mensagem 1 Mensagem 2 Mensagem 3

HOJE Mensagem 1 Mensagem 2 Mensagem 3

Today, what I have is working like this:

ONTEM Mensagem 1 ONTEM Mensagem 2 ONTEM Mensagem 3

HOJE Mensagem 1 HOJE Mensagem 2 HOJE Mensagem 3

Today I'm using the following code:

<?php
$dt_cadastro = strtotime($linha['dt_cadastro']);
$hoje_inicio = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
$hoje_fim = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
$ontem_inicio = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
$ontem_fim = mktime(23, 59, 59, date('m'), date('d') - 1, date('Y'));
$anteontem_inicio = mktime(0, 0, 0, date('m'), date('d') - 2, date('Y'));
$anteontem_fim = mktime(23, 59, 59, date('m'), date('d') - 2, date('Y'));
?>
<?php if (($dt_cadastro >= $hoje_inicio) AND ($dt_cadastro <= $hoje_fim)): ?>
<span class="chat-data" style="position:absolute; left:45%; padding-bottom: 0px;">                                                                    
<span class=""><?= 'HOJE' ?></span>
</span>
<?php elseif (($dt_cadastro >= $ontem_inicio) AND ($dt_cadastro <= $ontem_fim)): ?>
<span class="chat-data" style="position:absolute; left:45%; padding-bottom: 0px;">
<span class=""><?= 'ONTEM' ?></span>
</span>
<?php elseif (($dt_cadastro >= $anteontem_inicio) AND ($dt_cadastro <=  anteontem_fim)):
?>
<span class="chat-data" style="position:absolute; left:45%; padding-bottom: 0px;">                                                                    
<span class=""><?= 'ANTEONTEM' ?></span>
</span>
<?php endif; ?>

This is inside a foreach

<?php foreach ($historico as $linha):?><br>
<?php endforeach;?>

PS: If there is another alternative to make the code cleaner and less repetitive, I'd like you to help me too, please.

    
asked by anonymous 08.02.2017 / 20:34

1 answer

2

First declare an auxiliary variable before foreach : $hoje1 = 0; . Then you change as soon as it should work:

<?php if($hoje1 == 0) { $hoje1 = 1; ?><span class="">HOJE</span><?php } ?>

Do the same for yesterday and the day before.

(I changed the word today to HTML)

    
08.02.2017 / 21:07