Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding PHP type coercion

I saw this small piece of code that is evading my understanding:

<?php

$a = '0e462097431906509019562988736854';
$b = '0e830400451993494058024219903391';

var_dump($a == $b);

Which will output:

bool(true)

I understand that when using ==, PHP will attempt fuzzy comparison, silently converting between types in order to perform the comparison. What I'm not understanding is why PHP seems to think these two strings are the same. I would have thought since $a and $b are strings, that no type conversion would need to take place.

What am I not understanding?

like image 893
amphetamachine Avatar asked Nov 04 '14 17:11

amphetamachine


2 Answers

I think this article explains it pretty well:

Type-coercing comparison operators will convert numeric strings to numbers

Just to quote the main issue here:

According to php language.operators.comparison, the type-coercing comparison operators will coerce both operands to floats if they both look like numbers, even if they are both already strings:

where both strings are using exponential notation, hence are treated as numeric strings, making loose comparison (==), coerce these strings to floats before actually "loosely" comparing them.

As a best practice and to prevent unexpected behaviour, always try to use identity equality (===), especially when dealing with strings.

like image 134
Kypros Avatar answered Sep 28 '22 01:09

Kypros


PHP attempts to convert to type float because the string begins with a 0. It stops after 0 because the next character is not a number. The same thing happens when you use type coercion to convert scientific notation to integer:

$x = (float)"12E-1x";  // $x == 1.2
$x = (int)"12E-1x";  // $x == 12 (stops at E because it's not an integer)
like image 35
Brandon Johnson Avatar answered Sep 28 '22 00:09

Brandon Johnson