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.
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!
CodePudding user response:
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>";
}
}
?>