0

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.

Apul Gupta
  • 3,044
  • 3
  • 22
  • 30
AVC
  • 67
  • 9
  • Why don't you just compare `'1' === '1'`, i.e. surround the `1` with single quotes? – danmullen Oct 28 '14 at 11:48
  • == are used to compare values if they are equal and it is less strict than ===. – Robin Oct 28 '14 at 11:52
  • I can not do this because all these are generated at run time and no control over values generated. Do you mean to append '' for all and compare? if so it work as it compare everything as string. so is that better way or using strcmp? – AVC Oct 28 '14 at 11:53
  • === are used to compare two values and also sees that both the values have the same data-type. === is more better to use than == if you want your values to match exactly. – Robin Oct 28 '14 at 11:54
  • this is how php comparision works.... don't like it? change the language perhaps? – itachi Oct 28 '14 at 11:55
  • @Robin, i need comparision based on values and no need to have same data types. so ideal choice is ==. but cases like '1x'== 1 are failing where i expect false due to same values – AVC Oct 28 '14 at 11:56
  • @itachi, its not about i like it or not. I am trying to solve a problem in php and any help is appreciated. – AVC Oct 28 '14 at 11:57
  • possible duplicate of [What's the difference between equal?, eql?, ===, and ==?](http://stackoverflow.com/questions/7156955/whats-the-difference-between-equal-eql-and) – iatboy Oct 28 '14 at 12:00
  • @iatboy no ,its not duplicate i believe. – AVC Oct 28 '14 at 12:06

3 Answers3

4

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

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
3

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

Apul Gupta
  • 3,044
  • 3
  • 22
  • 30
0

Please try the following :

if(strlen($x) == 1) {
    if ((intval($x) === 1)) {
        echo "Equals";
    }
    else
   {
        echo "Not Equals";
   }
}
   }else
   {
       echo "Not Equals";
   }
Robin
  • 471
  • 6
  • 18