sergio
sergio

Reputation: 5250

Comparing arrays giving different results

I have the following PHP code:

$a = "5";
$b = array("position"=>1);
var_dump("5" <= $b);
var_dump("5" <= "Array");
var_dump("Z" <= $b);
var_dump("Z" <= "Array");

the result is:

boolean true
boolean true
boolean true
boolean false

We know that array is converted to the string array. What's actually happening during the conversion? Why are the results different in the cases below?

var_dump("Z" <= $b); // (in this case array convert to string "array")
var_dump("Z" <= "Array");  // (in this case string "Array" )

But the result is different. Why?

Upvotes: 2

Views: 77

Answers (2)

Amal Murali
Amal Murali

Reputation: 76636

Consider the following two expressions:

var_dump("Z" <= $b);
var_dump("Z" <= "Array");

In the first expression, you're comparing a string and an array. This comparison will always return TRUE. As the PHP manual says, if any comparison is made between two operands where one of them is an array, the expression will always evaluate to TRUE. If both the operands are arrays, then the array with fewer members is considered smaller.

In the second expression, you're comparing Z to a literal string Array. In this case, the strings are first converted to numbers before the comparison is made. This is usual math and the result is as expected. Since Z comes after A in the alphabet series, it'd return FALSE.

Upvotes: 1

meze
meze

Reputation: 15097

As the manual states:

Comparison with Various Types

array | anything | array is always greater

When both operands are strings, string comparison rules are applied.

So no matter what the first operand is, < array() is always true

Upvotes: 2

Related Questions