P
P
pentarh2013-03-28 22:17:17
PHP
pentarh, 2013-03-28 22:17:17

PHP strange == operator behavior

Just wondering why the code

<?php echo 0 == 'sell'?'true':'false';

evaluates to true?

PHP 5.4.12, 5.3.19

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
Andrey Burov, 2013-03-28
@BuriK666

because, the second argument in the == operator is cast to the type of the first argument, hence (int)'sell' === 0 hence 0 == 0 gives true.

M
Max T, 2013-03-28
@Maksimus2000

The right operand is converted to number, more details here
php.net/manual/ru/language.operators.comparison.php

N
Nikita Gusakov, 2013-03-28
@hell0w0rd

Not a bug. Use === when precision is important

F
for93t, 2013-03-28
@for93t

And yet, for example, you cannot check the occurrence of a substring in a string using expressions like:

if (!strpos($haystack, $needle) {

because the string may begin with the substring you are looking for, and the function will return 0, which, without an explicit type comparison (operator ===), will not allow the condition to work correctly.
In general, PHP's loyalty to variable types can be the cause of some rather insidious bugs. So you need to have at least a basic understanding of comparing variables of different types in order not to step on this rake.

F
for93t, 2013-03-29
@for93t

wrong thread, sorry

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question