Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to include an element inside a foreach and indicate that it should not be repeated in each result?

I read the rest documentation; and to continue; but it doesn’t seem to work with this requirement.

<?php  
$colors = array("red", "green", "blue", "yellow"); 

foreach ($colors as $value) {
?><p>TITLE</p><?php
 echo "$value <br>";
}
?> 

Output:

TITLE
red

TITLE
green

TITLE
blue

TITLE
yellow 

I thought that with break or continue it would be possible but it seems that it is not what I need or I did not understand it exactly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need (including the title inside the foreach to avoid longer code like an if condition):

TITLE
red

green

blue

yellow 

Do you know any correct way to achieve this? Thanks!

>Solution :

Even with the comments on the question, it’s still not clear to me why you wouldn’t just gate this all with a simple if. If you insist on continuing with this design, you can check the $index of the current item you’re iterating on in the foreach loop and if it’s the first one, echo TITLE along with it:

<?php  
$colors = array("red", "green", "blue", "yellow"); 

foreach ($colors as $key=>$value) {
  if ($key === 0) echo "<p>TITLE</p>";
  echo "$value <br>";
}
?> 

In my personal opinion, however, it would be much more readable if you simply gated the entire block here:

<?php  
$colors = array("red", "green", "blue", "yellow"); 

if (count($colors) > 0) {
  echo "<p>TITLE</p>";
  foreach ($colors as $value) {
    echo "$value <br>";
  }
}
?> 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading