代码之家  ›  专栏  ›  技术社区  ›  Gagantous Faradox

从内部循环php中断循环

  •  0
  • Gagantous Faradox  · 技术社区  · 7 年前

    我有这样的数组,我用它来生成循环。我想打破这些循环,当它们有值“am”时,我该怎么做呢?

    Array
    (
        [0] => A
        [1] => B
        [2] => C
        [3] => D
        [4] => E
        [5] => F
        [6] => G
        [7] => H
        [8] => I
        [9] => J
        [10] => K
        [11] => L
        [12] => M
        [13] => N
        [14] => O
        [15] => P
        [16] => Q
        [17] => R
        [18] => S
        [19] => T
        [20] => U
        [21] => V
        [22] => W
        [23] => X
        [24] => Y
        [25] => Z
        [26] => AA
        [27] => AB
        [28] => AC
        [29] => AD
        [30] => AE
        [31] => AF
        [32] => AG
        [33] => AH
        [34] => AI
        [35] => AJ
        [36] => AK
        [37] => AL
        [38] => AM
        [39] => AN
        [40] => AO
        [41] => AP
        ...
        [726] => ZZ
    )
    

    这是我的语法

    $alp = range("A","Z");
    $hit = count(range("A","Z"));
    for($i=0; $i < count(range("A","Z")); $i++) { 
        for ($i2=0; $i2 < count(range("A","Z")); $i2++) { 
    
            $alp[$hit++] = $alp[$i].$alp[$i2];
             if($alp[$hit] == "AM"){
                break;
               }
    
        }
        $hit++;
    };
    

    我得到了一个错误,比如未定义的偏移量等,直到循环结束,当我在一个循环中中断循环时,如何才能中断所有的循环?

    2 回复  |  直到 7 年前
        1
  •  1
  •   u_mulder    7 年前

     $alp[$hit++] = $alp[$i].$alp[$i2];
     // $hit is already increased.
     // Therefore `$alp[$hit]` does not exist
     if($alp[$hit] == "AM"){
        break;
     }
    

     $alp[$hit] = $alp[$i].$alp[$i2];
     // $hit is still the same
     if($alp[$hit] == "AM"){
        // `break` will stop inner `for` loop (with $i2)
        break;
        // use `break 2;` to break both `for` loops
     }
     $hit++;
    
        2
  •  1
  •   Vishal Kumar    7 年前

     $alp[$hit++] = $alp[$i].$alp[$i2];
     // In $alp array you have any 26 items as per your count.
     // here $hit is 27 and in your $alp there is only 26.
     // so you just need to push the new variables in and then check
    
     array_push($alp,$alp[$i].$alp[$i2]);
    
     // Now check `$alp[$hit]`.
     if($alp[$hit] == "AM"){
        break;
     }
    

    $alp = range("A","Z");
    $hit = count(range("A","Z"));
    
    for($i=0; $i < count(range("A","Z")); $i++) { 
        for ($i2=0; $i2 < count(range("A","Z")); $i2++) { 
    
            array_push($alp, $alp[$i].$alp[$i2]);
    
            if($alp[$hit] == "AM"){
                // echo $alp[$hit];
                // Here is the First Break
                break 2; // it breaks all loops;
            }
        }
        $hit++;
    };
    
    推荐文章