How does the “Array dereferencing” work on a scalar value of type boolean/integer/float/string as of PHP version 7.2.0?

◇◆丶佛笑我妖孽 提交于 2019-12-01 01:13:09

They are referring to non-complex types such as int or float.

In your example you are using an array. So you don't see the issue.

<?php
function getArray() {
    return array(1, 2222, 3);
}
$secondElement = getArray()[1]; // 2222

$null = $secondElement[123456]; // 123456 can be any number or string
var_dump($null);

// similarly:
$also_null = getArray()[1][45678];
var_dump($also_null);

The first pair of brackets is array-dereferencing on the array (1, 2222, 3), the second is array-dereferencing on an integer (2222) which always returns null.

Simplified:

<?php
$a = 123456;
var_dump($a[42]); // is null
$a = 123.45;
var_dump($a[42]); // is null
$a = true;
var_dump($a[42]); // is null
$a = null;
var_dump($a[42]); // is null

This "fails silently" as in theory you should get an error from this, rather than just null.

Also happens with null, other than int, float, bool:

<?php 
$a = true;
var_dump($a[42][42][42][42][42][42][42][42]); // also null, and no errors

But works correctly instead with arrays and strings.

<?php
$a = "abc";
var_dump($a[1]); // b
$a = [11, 22, 33];
var_dump($a[1]); // 22

Answering your question, "How does the “Array dereferencing” work on a scalar value of type": It doesn't, it just returns null instead of returning an error of some sort.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!