RSS

  • YouTube
  • LinkedIn
  • Google

PHP Comparison Error

Compartilhe em suas mídias sociais
  •  
  •  
  •  
  •  

Today, I was writing a script in PHP to be used in the command line when I came across unexpected behavior (at least on my part).
The script should receive three arguments, the last of them a list containing one or more numeric codes.
Trying to validate this last argument was getting a different result than imagined.
See the code snippet that I was using:

Interestingly, when I ran

the result was

and reversing the condition to

show the expected message.
I tried to assign to a separate variable and still continued not working.

Whyyy??

The Type Comparison !== cannot be used here, since all arguments will be strings. When I though about this I got the answer.

So I did some command line tests and I check for the actually behavior of PHP Comparisons.

When we do things like: $string == $integer PHP will always do a CAST from String to the other type before comparison, so the code $string == (int) $string will always return true, since $string will be changed to int in both sides.

To avoid this kind of trouble, is necessary to have the same type in both sides of comparison.

See you.


Compartilhe em suas mídias sociais
  •  
  •  
  •  
  •  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.