tree em
tree em

Reputation: 21701

String comparison behaves differently

$x = array(3) {
   [0]=>       "A - 1"
   [1]=>       "B - 4"
   ["Total"]=>     "5"
 }

TRY:

foreach($x as $k=>$v){
   if($k=="Total"){break;}
    echo $v."<br>";
 }

Because I just want to output :

A - 1
B - 4

But I don't see anything in the output.

what do I wrong?

thanks

Upvotes: 2

Views: 132

Answers (2)

codaddict
codaddict

Reputation: 454930

You get nothing in the output as you break out of the loop the very fist time.

In the first iteration $k with value 0 which is numeric is compared with "Total" which is a string and this comparison returns true because PHP will convert the string "total" to a number before comparison and "total" when converted to number is 0.

Ideone

To fix this don't use ==, use strcmp instead which will convert the numeric keys to string before comparison or you can use === which checks type as well as value.

Ideone

Upvotes: 5

Shaun
Shaun

Reputation: 2311

Put echo $v."<br>"; in an else statement......

Upvotes: -1

Related Questions