[PHP] Compare string to 0 in PHP

The question seems simple and naif but if you really do it, it’s a little annoying.

You may going to met this kind of case :

if('your_string' == 0) {
 echo "The result of 'your_string' == 0 is Equivalent\n";
} else {
 echo "The result of 'your_string' == 0 is Not Equivalent\n";
}

if('your_string' == 1) {
 echo "The result of 'your_string' == 1 is Equivalent\n";
} else {
 echo "The result of 'your_string' == 1 is Not Equivalent\n";
}

if('your_string' == '0') {
 echo "The result of 'your_string' == '0' is Equivalent\n";
} else {
 echo "The result of 'your_string' == '0' is Not Equivalent\n";
}

if('your_string' == '1') {
 echo "The result of 'your_string' == '1' is Equivalent\n";
} else {
 echo "The result of 'your_string' == '1' is Not Equivalent\n";
}

In my post, the result is :
The result of ‘your_string’ == 0 is Equivalent
The result of ‘your_string’ == 1 is Not Equivalent
The result of ‘your_string’ == ‘0’ is Not Equivalent
The result of ‘your_string’ == ‘1’ is Not Equivalent

So you see here, the first check is true, that we don’t want.
To avoid the problem, what you have to do is compare with the type, like :

if("your_string" === 0) ...

if( strval(</span>"your_string") === 0) ...
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s