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 '-'
?
== 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.
Comparison operators — operators that compare values and return true or false . The operators include: > , < , >= , <= , === , and !== .
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.
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;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With