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.

9
  • Why don't you just compare '1' === '1', i.e. surround the 1 with single quotes? Commented Oct 28, 2014 at 11:48
  • == are used to compare values if they are equal and it is less strict than ===. Commented Oct 28, 2014 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? Commented Oct 28, 2014 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. Commented Oct 28, 2014 at 11:54
  • this is how php comparision works.... don't like it? change the language perhaps? Commented Oct 28, 2014 at 11:55

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, even i was having the same opinion. will wait for some other views also now
hmm..its little complicated.
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

1 Comment

@AVC For case insensitive search, use strcasecmp as mentioned in answer.
0

Please try the following :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.