简体   繁体   中英

$myArray = array() vs. []

I found this "modern" version of defining an array in the sources of laravel 5. Are there any advantages of doing it this way?

// the traditional way
$arrEmpty = array();
$arrFilled = array(
    'a' => 'apple'
);

// the 'modern' way
$arrEmpty = [];
$arrFilled = [
    'a' => 'apple'
];

The 'new' way does not seem to be standard, so I couldn't use this one on PHP 5.3. Any doc-links are welcome.

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

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

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

Following [] is supported in PHP 5.4

Square bracket array shortcut - keys and values are separated by colons:

$a = [1, 2, 3];
$b = ['foo': 'orange', 'bar': 'apple', 'baz': 'lemon'];

Square bracket array shortcut - keys and values are separated by double arrows:

$a = [1, 2, 3];
$b = ['foo' => 'orange', 'bar' => 'apple', 'baz' => 'lemon'];

This is a short syntax only and in PHP < 5.4 it won't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM