Reputation: 21
Today I found a strange if statement that reports true without errors in PHP7. See the example below;
<?php
$array = array();
// This is true
if (!is_array($array)['key']) { echo 'test1'; }
// Strangely, this reports false
if (true['key']) { echo 'test2'; }
// This also reports true
if (!(1)['key']) { echo 'test3'; }
// Knowing the statement must be false (!(1)), you would think that false works; it doesn't
if (false['key']) { echo 'test4'; }
Can someone explain why it reports test1 and test3 as true when it is clearly faulty code without throwing errors? It did on PHP 5.6 for all statements except the first one (test1).
Upvotes: 0
Views: 67
Reputation: 54831
Answer is
var_dump(is_array($array)['key'], true['key'], (1)['key'], false['key']);
And it is
NULL, NULL, NULL, NULL
And a man string:
For any of the types integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words,
(array)$scalarValue
is exactly the same asarray($scalarValue)
.
Upvotes: 1