-1

I want to know why the following expression is evaluated to true.

var_dump(('a' == 0)); //bool(true)
Dumitru
  • 116
  • 1
  • 8
  • 2
    Do a `echo (int) 'a';` and you will understand better. – leninhasda Oct 27 '16 at 07:38
  • 2
    when strings are compared with integers, they are automatically casted as integer, and if they don't contain a number, the result of that casting is 0. and `0 == 0` - that's why you never compare a string with an integer - and if you have to, you use the strict comparison: `'a' === 0` is false. – Franz Gleichmann Oct 27 '16 at 07:44

2 Answers2

6

String conversion to numbers (from the PHP manual, emphasis mine)

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

Examples :

var_dump(('a' == 0)); //bool(true)
var_dump(('a' === 0)); //bool(false)
var_dump(('aaaa' == 0)); //bool(true)
var_dump(('1aaaa' == 1)); //bool(true)
var_dump(('18aaaaa' == 18)); //bool(true)
Bram
  • 2,515
  • 6
  • 36
  • 58
roberto06
  • 3,844
  • 1
  • 18
  • 29
1

you may expect this

<?php
var_dump('a' === 0);

https://eval.in/667364

LF00
  • 27,015
  • 29
  • 156
  • 295