1

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.

6
  • 1
    Simpler, easier to read, similar to js syntax Commented Jul 13, 2015 at 9:41
  • "modern" version of defining an array in laravel 5 . It is not laravel. It is PHP. Commented Jul 13, 2015 at 9:41
  • The new way is only as standard as the fact that some libraries frameworks still support older PHP versions where the short array syntax isn't available, so they can't use it Commented Jul 13, 2015 at 9:41
  • @b0s3 I know that it is PHP, I wrote I found [...] in laravel 5 Commented Jul 13, 2015 at 9:45
  • // the 'laravel' way $arrEmpty = []; Really? Commented Jul 13, 2015 at 9:46

2 Answers 2

2

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",
];
?>
Sign up to request clarification or add additional context in comments.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.