AVC
AVC

Reputation: 77

comparison in php using == and === operators

In my application, there are values generated at run time like x, 1x,2,1 etc. I need to compare these:

as we know,

        x  == 1  is false   
       '1x'== 1  is true
       '1' == 1  is true 

for my application, the first,second cases needs to be false and third needs to be true. if I use ===,

       x  === 1    is false   
      '1x'=== 1    is false   
      1'  === 1    is false  

So both these comparisons i can not use.

I think converting to string and then comparing using strcmp will be the best option I have. Please share your thoughts. Any reply is appreciated.

Upvotes: 0

Views: 81

Answers (3)

Robin
Robin

Reputation: 471

Please try the following :

if(strlen($x) == 1) {
    if ((intval($x) === 1)) {
        echo "Equals";
    }
    else
   {
        echo "Not Equals";
   }
}
   }else
   {
       echo "Not Equals";
   }

Upvotes: 0

Apul Gupta
Apul Gupta

Reputation: 3034

Use either strcmp or strcasecmp:

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. Reference

Upvotes: 3

Sougata Bose
Sougata Bose

Reputation: 31739

strcmp would be suitable for this.But you should be aware of its return values.

Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

or you can also use Regex

Upvotes: 4

Related Questions