“中断”无法按预期工作


"break" doesn't work as expected

我想检查comment数组的字符串长度。一旦它们中的任何一个等于或高于 4,我想回显相关值,然后停止。

我猜使用while应该很好,但是如果我在4或更多时打破循环,则不会有任何回声。如果我在 5 或更多时打破它,前两个 4 弦值将被回显,但我只希望前 4 弦值得到回显,然后停止。

$comment[1] = "abc";  // add comment below text button
$comment[2] = "xyz";  // add comment below text button
$comment[3] = "abcd";  // add comment below text button
$comment[4] = "xyza";  // add comment below text button
$comment[5] = "abcde";  // add comment below text button
$comment[6] = "xyzab";  // add comment below text button
$x = 1;
while ($x <= 10) {
    if (strlen((string)$comment[$x]) >= 4 ) {
        echo $comment[$x];
        echo "<br/>";
    }
    $x = $x + 1;
    if (strlen((string)$comment[$x]) >= 4) break; // Nothing get echoed
 // if (strlen((string)$comment[$x]) >= 5) break; // two values get echoed
} 

另外,是否有更好/更短的做法来检查这个东西,也许是一些内置函数,如in_array

代码的问题在于,循环体检查/打印一个元素并在另一个元素上中断,因为您在这两点之间增加了指针。您可以将 break 语句移到增量上方,甚至可以将其放入 if 语句中(很像 @A-2-A 建议的那样)。然后它应该按预期工作。

突破增量:

while ($x <= 10) {
    if (strlen((string)$comment[$x]) >= 4 ) {
        echo $comment[$x];
        echo "<br/>";
    }
    if (strlen((string)$comment[$x]) >= 4) break; 
    $x = $x + 1;
} 

使用组合回声/中断:

while ($x <= 10) {
    if (strlen((string)$comment[$x]) >= 4 ) {
        echo $comment[$x];
        echo "<br/>";
        break;
    }
    $x = $x + 1;
} 

此外,您可能希望迭代数组的长度,而不是硬编码限制 10:

$x = 0;
$length = count($comment);
while ($x < $length) {
   // ... 
}