Odd thing with a very simple code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pish
Forum Newbie
Posts: 4
Joined: Sun Feb 21, 2010 1:25 am

Odd thing with a very simple code

Post 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!
anantha
Forum Commoner
Posts: 59
Joined: Thu Dec 23, 2010 7:38 pm

Re: Odd thing with a very simple code

Post 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...
pish
Forum Newbie
Posts: 4
Joined: Sun Feb 21, 2010 1:25 am

Re: Odd thing with a very simple code

Post 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
Post Reply