Loop loop issues in php

Here is the code I have: (p just echos plus adds a new line)

foreach ($vanSteps as $k => $reqInfo) { p($k); if ('van' == $k) { p('The key is the van, continue'); continue; }//continue if we reached the part of the array where van is key //do stuff } 

and I get this output:

 0 The key is the van, continue 1 2 3 van The key is the van, continue 

Why does the if statement return true when the key is 0? This foreach loop handles the logic that is applied when the key == 0 (and any key other than the "van" key), and this will ruin the logic because it returns true when the key is 0.

Any help?

Thanks.

+7
source share
7 answers

Use === for this comparison. When PHP compares a string and an integer, it first distinguishes the string to an integer value, and then performs the comparison.

See comparison operators in the manual.

+12
source

In PHP, 'van' == 0 is true . This is because when == used to compare strings and numbers, the string is converted to a number (as described in the second link below); this makes an internal comparison 0 == 0 , which of course is true .

The recommended alternative for your needs would be to use strict equality comparison with === .

See Comparison Operators and Converting Strings to Numbers

+6
source

In PHP, when you compare 2 types, it must convert them to the same type. In your case, you are comparing string with int . Internally, this translates to

if((int)'van'==0).... and then if((int)'van'==1)....

(int) "any possible string" will be 0 :) Thus, you need to either manually convert both values ​​to the same type, or use === as a comparison operator instead of a free = , an exception to this rule (as indicated in comments) it would be if the line starts with a number or can be interpreted as a number in any way (1, 0002, -1, etc.). In this case, the string will be interpreted as a number defining the end of the non-numeric end of the string

See http://php.net/manual/en/types.comparisons.php for more details.

+2
source

This works great:

 $array = array(0=>"a",1=>"b","van"=>"booya!"); function p($v){ echo "{$v}<br />"; } foreach ($array as $k => $reqInfo) { p($k); if ('van' === $k) { p('The key is the van, continue'); continue; }//continue if we reached the part of the array where van is key //do stuff } 

Output:

 0 1 van The key is the van, continue 

Pay attention to === .

0
source

Read Comparison with tables of different types. When one of the operands is a number, the other operand is also converted to a number. Since "van" is a non-numeric sting, it converts to 0. You must use the === operator in this case, which also checks the type of the variable

0
source

His interpretation of 'van' as a boolean ( false ), which is 0.

To check for exact type and value matches in PHP, you should use === instead of ==

0
source

This is because of 'van' == 0 (true).

Instead, you should use 'van' === 0 (false).

In short, use === instead of ==.

0
source

All Articles