I have an echo for each number X of the Foreach Php

Asked

Viewed 40 times

-2

I’m trying to find a logic to my problem I have the following foreach

 foreach ($Read->getResult() as $LastPDT):
    echo "a";
 endforeach;

in this example if you have 30 record it will print on the screen 30 times the word "a" right. what I want is that every 5 record in the foreach it of one more echo example

a
a
a
a
conteudo
a
a
a
a
conteudo
a
a
a
a
conteudo

I did it that way

$contador = 0
foreach ($Read->getResult() as $LastPDT):
  $contador ++;
   if($contador == 5):
     echo "conteudo";
    endif;
echo "a";
endforeach;

when executing returns the following result

 a 
 a 
 a 
 a 
 conteudo
 a 
 a 
 a 
 a 
 a 
 a 
 a
 a
 a 
 a

it shows echo only in the first and does not continue the show every 5

1 answer

3


Missed only you to reset your counter inside your IF.

$contador = 0
foreach ($Read->getResult() as $LastPDT):
  $contador ++;
   if($contador == 5):
     echo "conteudo";
     $contador = 0; // Zerando contador aqui
    endif;
echo "a";
endforeach;
  • 1

    Our thanks hadn’t thought of that

Browser other questions tagged

You are not signed in. Login or sign up in order to post.