0

I have array like this that i produce using for loops. I want to break the loops, when they have value "AM", How could i do that ?

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
)

This is my syntax

$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++;
};

I got an error, like undefined offset and such until the end of looping, how could i break all the loop when i break the loop inside a loop ?

1

2 Answers 2

1

In your code:

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

Replace with something like:

 $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++;
Sign up to request clarification or add additional context in comments.

Comments

1

You Code

 $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;
 }

Try This Code.

$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++;
};

3 Comments

it didnt break both loop
Use break 2; instead of break inside the second loop.
still not working, it's loop until [676] => ZZ, i want if the $alp[$hit] == "AM", then break, so it's only have 37 key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.