Sven van den Boogaart
Sven van den Boogaart

Reputation: 12323

php comparison operator in assignment

I saw a small php quiz online that contained the following code:

$somevalue[[ 2 <=['-']=> 2][1]] = $somestring;

My question is, what does the part before the assignment do?

$somevalue[[ 2 <=['-']=> 2][1]] 

<= looks like the comparison operator but in that case it is comparing 2 to '-'?

Upvotes: 7

Views: 165

Answers (2)

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

To understand this you need to break the statement in parts,

echo 2 <=['-'];//return true

PHP Comparison operator

After this the statement will be

$somevalue[[1 => 2][1]] = $somestring;

Here you see the array index 1 has values 2. After this the last index which is 1, from the array [1 => 2] it will return 2, so finally you will have

$somevalue[2] = $somestring;

Upvotes: 4

Sean Bright
Sean Bright

Reputation: 120634

PHP's array initialization syntax looks like this:

$arr = [ key => value ];

So in this part:

2 <=['-']=> 2

The 'key' is the result of the expression 2 <= ['-'], which according to this page evaluates to true (an array is always greater than what you are comparing it to, unless it's another array). Because PHP arrays keys are either integers or strings, the boolean result is implicitly cast to the integer 1, so you end up with:

1 => 2

So the simplified expression:

[ 1 => 2 ][1]

Will evaluate to the second element of the array we've just created (PHP array's are 0-based), so this will simplify to:

2

So at the end we end up with:

$somevalue[2] = $somestring;

Upvotes: 10

Related Questions