João Silva
João Silva

Reputation: 167

PHP - string vs array comparison

I'll post a question and I hope the administrators stackoverflow do not put this as a duplicate topic , because I find no explanation for such a thing .

All we know that after the type- juggling this comparison looks like this:

false == array() -> (bool) == false (bool) array() -> false == false -> true

So far, nothing unusual.

The problem was trying to ask for an explanation for such a thing but the answers did not have senses and then it seemed that the topic was duplicated , but actually it is not a duplicate topic.

The question was how the php interprets this comparison below:

'' == array()

Some people said:

"A cast is done to the empty string to array"

The result is:   (array) '' == array() -> array('') == array() -> false

Seems to be right.

But the big problem is here, below:

'' == array('')

Because it does not return true ? If by some theory:

'' == array('') -> This should return true

'' == array('') -> (array)'' == array('') -> array('') == array('')

But false is returned.

Can you explain once and for all this issue ?

Upvotes: 2

Views: 914

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173582

tl;dr no casting is performed in the comparison:

Internally the comparison is done via compare_function, which is called when the parser sees a == operator.

Inside this function a test is done based on the type of each operand; the combination of string and array doesn't have a specific behaviour, so a numeric conversion is attempted here.

This attempt fails for both operands, because an empty string is not numeric and an array isn't either. It then performs another test here to check whether any operand is an array or an object. If so, it either returns -1 or 1, depending on which operand matched.

Of course, this is also documented in the manual to help those who don't want to decipher the source code :)

Upvotes: 3

Related Questions