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

后端 未结 1 1383
攒了一身酷
攒了一身酷 2021-01-07 00:11

I am using PHP 7.2. I come across the following note from the arrays chapter of PHP Manual

Array dereferencing a scalar value which is not a string s

相关标签:
1条回答
  • 2021-01-07 01:02

    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.

    0 讨论(0)
提交回复
热议问题