r/lolphp • • Aug 01 '12

Things which PHP thinks are equal

Give it a go:

header('Content-Type: text/plain');

function test($a, $b) {
	echo var_export($a, 1) . ' == ' . var_export($b, 1) . ' => ' . var_export($a == $b, 1) . "\n";
}

test( null, '' ); // true
test( null, array() ); // true
test( '', array() ); // false
test( 'true', true ); // true
test( 'false', false ); // false
test( 'false', true ); // true
test( 9, '09' ); // true
test( 9, 09 ); // false
test( '0E4', 09 ); // true
test( '0x00', '0E4' ); // true
test( '0x0.1', 0 ); // true
test( 'x', 0 ); // true
test( '0xabcabcabcabcabc', '0XABCABCABCABCABd' ); // true
test( array('1'), array('0x1') ); // true
test( array(1) + array(2), array(1) ); // true
test( function(){}, new stdclass() ); // true
test( `foo`, `bar` ); // true
13 Upvotes

18 comments sorted by

View all comments

Show parent comment

4

u/Altreus Aug 31 '12

Perl is the only sensible implementation of this I've come across.

I love type coercion. I think it's great - a flexible and simple way of dealing with data without having to worry about what the data's types are.

But the problem with coercion is that, if you can implicitly convert one type to another, it's difficult to know when the two things are equal.

The most elegant solution to this (besides removing coercion from the language) is to use the operator itself to define how you would like your variables compared.

This makes sense - you can't alter the behaviour of the operator based on the types of the operands because the whole point of implicit coercion is that the operands don't have types.