How to echo some text inside a for-loop only once?
I have this piece of code
<?php for ($i=0;$i<sizeof($list["tags"]); $i++) {
if ($list["tags"][$i]["title"]=='list') {
echo 'Not correct type';
}
if ($list["tags"][$i]["title"]!='list') {
?>
<a href="...">Text</a>
<?php }
}开发者_开发问答
?>
My problem is that when $list["tags"][$i]["title"]=='list'
, I get the message 'Not correct type' many times as the loop continues. How can I echo that message only once?
You can insert break;
after the echo statement to exit the loop when the condition is met. Use break n;
to exit out of n layers of loops/conditionals.
You'll just have to keep track of whether you've already shown it or not:
$shown = false;
for ( $i = 0; $i < sizeof( $list['tags'] ); $i++ ) {
if ( $list['tags'][$i]['title'] == "list" && !$shown ) {
echo "Not correct type";
$shown = true;
}
if ( $list['tags'][$i]['title'] != "list" ) {
echo '<a href="...">Text</a>';
}
}
But this raises the question: why would you only want the message to show once? Wouldn't you want it to display "Not correct type" for all values of $i
for which the title is not "list"
?
精彩评论