【问题标题】:"break" doesn't work as expected“break”没有按预期工作
【发布时间】:2016-04-30 22:32:18
【问题描述】:

我想检查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

【问题讨论】:

    标签: php loops while-loop break


    【解决方案1】:

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

    在增量之上有break:

    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) {
       // ... 
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 2020-03-18
      • 2012-06-14
      • 2014-11-15
      • 1970-01-01
      • 2012-07-02
      • 2011-09-07
      • 2013-03-03
      • 2015-05-18
      相关资源
      最近更新 更多