Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP loose comparison with == [duplicate]

Tags:

php

I'm a curious programmer. So these days I was reading the documentation from the PHP site and this link was "PHP type comparisons" http://www.php.net/manual/en/types.comparisons.php

I decided to do some exercises to fill the tables of comparisons but there are some answers that I can not see why, for example:

<?php
var_dump(false == array()); // Okay, an empty array is considered false. True result
var_dump('' == array()); // false ? Why not true if an empty string is considered false ?
var_dump(0 == array()); // false ? Why ?
var_dump(null == array()); // true. Why ?
?>

Can you help me about this? I can not understand why some comparisons, I can not find anywhere explanation.

like image 833
João Silva Avatar asked Jun 27 '26 02:06

João Silva


2 Answers

Here is the reason why.

Case one will cast the array() to a boolean, resulting in false.

Case two and three are explained here, the scalars are cast to arrays:

For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

Case four is explained here:

Converting NULL to an array results in an empty array.

like image 130
Bart Friederichs Avatar answered Jun 28 '26 17:06

Bart Friederichs


It's all about type juggling, which type wins over the other type.

For instance, when you compare an number with a string, the number always wins so the string will be converted into a number. So "12abc" == 12 is true in PHP.

  1. When comparing a boolean (false) with something, that something is converted to a boolean. (bool) array() is false, so false == false is true.
  2. When comparing another value with an array, the other value is converted to array([0] => VALUE_OF_OTHER) (in other words, converted to an array). That means that the comparisation becomes array('') == array(), which is false
  3. Same as (2). array(0) == array() is false
  4. array(null) means just an array with nothing, thus array(null) == array() (which is the comparisation you did), so the result is true.
like image 28
Wouter J Avatar answered Jun 28 '26 17:06

Wouter J