php - Is it possible to include an element inside a foreach and indicate that it should not be repeated in each result?
one text
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>";
}
}
?>
Source