Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php comparison operator in assignment

Tags:

php

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 '-'?

like image 861
Sven van den Boogaart Avatar asked Jul 22 '19 12:07

Sven van den Boogaart


People also ask

What is == and === in PHP?

== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. Syntax: operand1 == operand2. === Operator: This operator is used to check the given values and its data type are equal or not.

What are the 5 comparison operators?

Comparison operators — operators that compare values and return true or false . The operators include: > , < , >= , <= , === , and !== .

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.


2 Answers

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;
like image 109
Sean Bright Avatar answered Oct 09 '22 13:10

Sean Bright


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;
like image 41
Rakesh Jakhar Avatar answered Oct 09 '22 13:10

Rakesh Jakhar