Reputation: 575
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);
}
Upvotes: 0
Views: 1600
Reputation: 76636
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.
Upvotes: 1
Reputation: 11354
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.
Upvotes: 2