Best way to initialize (empty) array in PHP

前端 未结 8 1602
悲&欢浪女
悲&欢浪女 2020-12-02 05:25

In certain other languages (AS3 for example), it has been noted that initializing a new array is faster if done like this var foo = [] rather than var foo

相关标签:
8条回答
  • 2020-12-02 05:35

    In ECMAScript implementations (for instance, ActionScript or JavaScript), Array() is a constructor function and [] is part of the array literal grammar. Both are optimized and executed in completely different ways, with the literal grammar not being dogged by the overhead of calling a function.

    PHP, on the other hand, has language constructs that may look like functions but aren't treated as such. Even with PHP 5.4, which supports [] as an alternative, there is no difference in overhead because, as far as the compiler/parser is concerned, they are completely synonymous.

    // Before 5.4, you could only write
    $array = array(
        "foo" => "bar",
        "bar" => "foo",
    );
    
    // As of PHP 5.4, the following is synonymous with the above
    $array = [
        "foo" => "bar",
        "bar" => "foo",
    ];
    

    If you need to support older versions of PHP, use the former syntax. There's also an argument for readability but, being a long-time JS developer, the latter seems rather natural to me.  I actually made the mistake of trying to initialise arrays using [] when I was first learning PHP.

    This change to the language was originally proposed and rejected due to a majority vote against by core developers with the following reason:

    This patch will not be accepted because slight majority of the core developers voted against. Though if you take a accumulated mean between core developers and userland votes seems to show the opposite it would be irresponsible to submit a patch witch is not supported or maintained in the long run.

    However, it appears there was a change of heart leading up to 5.4, perhaps influenced by the implementations of support for popular databases like MongoDB (which use ECMAScript syntax).

    0 讨论(0)
  • 2020-12-02 05:37

    In PHP an array is an array; there is no primitive vs. object consideration, so there is no comparable optimization to be had.

    0 讨论(0)
  • 2020-12-02 05:37

    What you're doing is 100% correct.

    In terms of nice naming it's often done that private/protected properties are preceded with an underscore to make it obvious that they're not public. E.g. private $_arr = array() or public $arr = array()

    0 讨论(0)
  • 2020-12-02 05:52

    There is no other way, so this is the best.

    Edit: This answer is not valid since PHP 5.4 and higher.

    0 讨论(0)
  • 2020-12-02 05:53

    Try this:

        $arr = (array) null;
        var_dump($arr);
    
        // will print
        // array(0) { }
    
    0 讨论(0)
  • 2020-12-02 06:01

    Prior to PHP 5.4:

    $myArray = array();
    

    PHP 5.4 and higher

    $myArray = [];
    
    0 讨论(0)
提交回复
热议问题