Page 1 of 1

Odd thing with a very simple code

Posted: Thu Feb 10, 2011 2:49 pm
by pish
Hi there.

I'm testing a very simple code. Basically I'm doing a foreach in an array which has no keys, there is only one field that has a key "email".
This is the code:

Code: Select all

$data_array = array($name0,$company0,'email'=>$email0,$comment); 
foreach($data_array as $field=>$data) { 
    if ($field == 'email') { 
        echo 'current field is email'; 
    } 
    else { 
        echo 'current field is not email'; 
    } 
}  
The odd thing is that the following sentence:

Code: Select all

if ($field == 'email') {  
returns TRUE when $field is 0 (zero)

I solved the problem replacing the sentence for this one:

Code: Select all

if ($field === 'email') {  
What I really like to know is why that sentence if ($field == 'email') { returns TRUE when $field is 0 ??

Thanks a lot!

Re: Odd thing with a very simple code

Posted: Thu Feb 10, 2011 3:44 pm
by anantha
This is true, because the string is casted interally to an integer. Any string (that does not start with a number), when casted to an integer, will be 0.according to http://php.net/manual/en/types.comparisons.php...see at the last post...

Re: Odd thing with a very simple code

Posted: Thu Feb 10, 2011 3:51 pm
by pish
anantha wrote:This is true, because the string is casted interally to an integer. Any string (that does not start with a number), when casted to an integer, will be 0.according to http://php.net/manual/en/types.comparisons.php...see at the last post...
Thanks anantha. Finally I got it, now it all makes sense! :)

Cheers