0

I'm trying to understand what the square brackets mean when trying to seed a database in Laravel. If I have a table with 2 fields title and body I'm wondering why square brackets are used instead of array(). Are the square brackets used for a short form or for organization? seems that square brackets aren't just used to seed a database.

public function run()
{
    $posts = [
      [ 'title' => 'My first post', 'body' => 'My post' ],
      [ 'title' => 'My second post', 'body' => 'My post' ]
    ];
    DB::table('posts')->insert($posts);
}
Kabu
  • 539
  • 2
  • 6
  • 18
  • See http://php.net/manual/en/language.types.array.php. "As of PHP 5.4 you can also use the short array syntax, which replaces array() with []." – Deinumite Jul 24 '13 at 17:27

2 Answers2

2

This is the same as:

public function run()
{
    $posts = array(
      array( 'title' => 'My first post', 'body' => 'My post' ),
      array( 'title' => 'My second post', 'body' => 'My post' )
    );
    DB::table('posts')->insert($posts);
}

It is the newer (>= PHP 5.4) short way of defining an array.

Geoffrey
  • 10,843
  • 3
  • 33
  • 46
1

What you're seeing is the short array syntax. It was implemented 2 years ago and is available for PHP versions => 5.4.

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

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

For compatibility, I suggest using the former. But both are functionally the same.

See the documentation for arrays here.

If you want more information, refer to the RFC.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150