PHP array vs [ ] in method and variable declaration

后端 未结 4 745
面向向阳花
面向向阳花 2020-12-14 14:39

I have a question about PHP syntax.

When defining functions and variables, which convention should I use?

I know they do the same thing in practice but I wou

相关标签:
4条回答
  • 2020-12-14 14:56

    just made a test to see how [] performs vs array() here is what I got

    testing 1 million []s ( with $arr[] = [] )
    started at : 1561298821.8754
    ended at: 1561298822.6881
    difference: 0.81266021728516 seconds 
    
    testing 1 million array()s ( with array_push( $arr, array()) )
    started at : 1561298822.6881
    ended at: 1561298823.843
    difference: 1.1549289226532 seconds 
    
    testing 1 million []s ( again while the processor is hotter)
    started at : 1561298823.8431
    ended at: 1561298824.7448
    difference: 0.9017219543457 seconds 
    

    so [] performed about 20% faster

    0 讨论(0)
  • 2020-12-14 15:03

    That depends on what version of PHP you are targeting. For the best backward compatibility, I'd recommend you to use array(). If you don't care about older versions (< PHP 5.4), I'd recommend you to use a shorter version.

    0 讨论(0)
  • 2020-12-14 15:04

    from PHP docs:

    As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

    <?php
    $array = array(
        "foo" => "bar",
        "bar" => "foo",
    );
    
    // as of PHP 5.4
    $array = [
        "foo" => "bar",
        "bar" => "foo",
    ];
    ?>
    

    if you'd try using '[]' notation in earlier version than 5.4, it will fail, and PHP will throw a syntax error

    for backward-compatibility you should use array() syntax.

    0 讨论(0)
  • 2020-12-14 15:13

    PSR-2 (by PHP Framework Interoperability Group) does not mention short array syntax. But as you can see in chapter 4.3 they use short array syntax to set the default value of $arg3 to be an empty array.

    So for PHP >= 5.4 the short array syntax seems to be the de-facto standard. Only use array(), if you want your script to run on PHP <5.4.

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