webster
webster

Reputation: 99

$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.

Upvotes: 1

Views: 756

Answers (2)

PHPhil
PHPhil

Reputation: 1540

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",
];
?>

Upvotes: 2

Ilanus
Ilanus

Reputation: 6928

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.

Upvotes: -1

Related Questions