Yannis
Yannis

Reputation: 922

break; does not work properly

I have this code:

foreach ($items as $key=>$value) {  

    if (strpos(strtolower($key), $text) !== false) {
            array_push($result, array("id"=>$value, "label"=>$key, "value"=>strip_tags($key)));
    }
    if ( count($result) > 2 )
        break;              
}

The break statement does not work so I get more than 2 items. However if I change the break; to

die('results more than 2');

it shows that it's working properly.

Am I using the break statement correctly?

Upvotes: 0

Views: 1054

Answers (3)

Mohammad Saberi
Mohammad Saberi

Reputation: 13166

Apply it and test the result :

if ( count($result) >= 2 ) break;

Upvotes: 1

Michael Laffargue
Michael Laffargue

Reputation: 10304

If you break with if ( count($result) > 2 ) then of course you'll have more than 2 items. If you want only two, just use if ( count($result) >= 2 )

Upvotes: 1

Rick Kuipers
Rick Kuipers

Reputation: 6607

Of course you get more than 2 items. You said if count($result) > 2 and not >= 2 So when you have more than 2 results, it breaks.

Upvotes: 9

Related Questions