Question

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);
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top