rockyraw
rockyraw

Reputation: 1145

"break" doesn't work as expected

I want to check the string length of comment array. Once any of them is equal or higher than 4, I want to echo the relevant value, and then stop.

I guessed that using while should be good, but if I break the loop at 4 or more, nothing gets echoed. If I will break it at 5 or more, the previous two 4-string values will be echoed, but I want only the first 4-string value to get echoed, and then stop.

$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

} 

Also, is there maybe a better/shorter practice to check this thing, maybe some built in function like in_array?

Upvotes: 1

Views: 93

Answers (1)

weirdan
weirdan

Reputation: 2632

The problem with your code is that your loop body checks/prints one element and breaks on different one because you increment the pointer between those two points. You could have moved your break statement above the increment, or even put it into that if statement (much like @A-2-A suggested). Then it should work as expected.

With break above the increment:

while ($x <= 10) {

    if (strlen((string)$comment[$x]) >= 4 ) {

        echo $comment[$x];
        echo "<br/>";

    }
    if (strlen((string)$comment[$x]) >= 4) break; 

    $x = $x + 1;
} 

With combined echo/break:

while ($x <= 10) {

    if (strlen((string)$comment[$x]) >= 4 ) {

        echo $comment[$x];
        echo "<br/>";
        break;

    }

    $x = $x + 1;
} 

Also you may want to iterate the array up to it's length instead of hardcoded limit of 10:

$x = 0;
$length = count($comment);

while ($x < $length) {
   // ... 
}

Upvotes: 2

Related Questions