1

Executing the following instruction in PHP 7.3 will return false.

',commaSeparatedString' >= '0' // => Result is false (evaluate strings)

If You compare against an integer 0, or do not put the comma at the beginning you get the expected results.

',commaSeparatedString' >= 0 // => Result is true (cast to integer)
'commaSeparatedString' >= '0' // => Result is true (evaluate strings)

Can someone explain what is PHP Doing in the under the hood to get to that result? I was expecting a different result. Thanks!

PD: If someone else come up with a better title for the question, feel free to edit it :)

ecarrizo
  • 2,758
  • 17
  • 29
  • 2
    Does this answer your question? [How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?](https://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp) – ArSeN Feb 20 '20 at 20:44
  • in the second example, the second example is missing the comma – Alberto Sinigaglia Feb 20 '20 at 20:46
  • @Berto99 Is not there in propose to demonstrate that if you compare a string without a comma at the beginning against a zero as string ('0') the result is true. – ecarrizo Feb 20 '20 at 20:47
  • and so the twos with the string at the right are just string comparison – Alberto Sinigaglia Feb 20 '20 at 20:48
  • @ecarrizo actually, it does - that is the point. Numerical value of , (44) is just smaller than that one of 0 (48), but not smaller than 0. – ArSeN Feb 20 '20 at 20:48
  • I got it. What I meant with my comment is the topic you mention, even if they mention the casting on comparison, it does not specify about how the strings are evaluated among them neither any of the links there make a mention about the ascii comparison. – ecarrizo Feb 20 '20 at 21:17

1 Answers1

4

When comparing with the , at the start, you will find that the ascii value of , is 44 (decimal) whereas the ascii value for 0 is 48.

So with a comma, the string is less than because the ascii value is less than, without the comma it starts with c which has an ascii value of 99, which is greater than 0.

ASCII table used from https://www.asciitable.xyz/

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Does this actually means that the whole value of a string when PHP is casting it is determined by its first character? – ecarrizo Feb 20 '20 at 20:54
  • 1
    Only when comparing strings do you have to take into account the ascii value, if you `echo (int)',commaSeparatedString';` or `echo (int)'commaSeparatedString';` they will both be 0. – Nigel Ren Feb 20 '20 at 20:57
  • Yeah I meant on the comparison of strings, good to know thanks – ecarrizo Feb 20 '20 at 21:29