5

I just reduced a crazy bug to what's in the title of this question. I'm sure there's a Perfectly Reasonable Explanation for why Php thinks that 0 == '%' (or any other special character, I think). I thought it would be good to get that explanation on StackOverflow!

2

5 Answers 5

7

It will do the same to any string, converting a non-number string to integer always gives 0.

1
  • Which is why (along with many other crazy things) PHP shouldn't even be considered a real "programming language".
    – slashCoder
    Aug 6, 2014 at 14:41
6

Using '===' (for exact, literal comparison -- the values must be the same type and also equal) instead of '==' solves this problem. With '==' it's trying to cast '%' to a number and 0 is the best it can do.

1
  • 1
    If you use ===, take care that $x = '0'; var_dump($x === 0) gives false ($x is string, 0 is an integer) :) Feb 24, 2010 at 0:20
1

In the event that a strict comparison operator is not directly suitable, if you want both values to be compared as strings, you can use strcmp(). An example could be where both values are variables, and the types might be either string, or int. Instead of type casting to string and then using strict equality check, strcmp() can be less verbose.

php's type coercion is very convenient. But if you don't understand its many rules(some can bite), you should try to avoid using it. See http://www.php.net/manual/en/types.comparisons.php

0

since '%' isn't true, it ought to be false (0), so of course 0=='%'

;-) funny though

1
  • It does not convert string to bool, another operand is integer and not bool. Feb 24, 2010 at 0:19
0

This is because it converts '%' to number and it is 0.

The way, however, how PHP converts strings to numbers is pure evil IMHO, because non number string does not have to result in zero.

If it starts with a digit then php will result the first number it can find in it and ignore the rest of the string. So:

"2 times 5 equals 10"

..will result in 2 when casted to a number.

Article in the documentation

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.