user6818018
user6818018

Reputation:

Redundant in declaring an array with array() and square brackets in PHP

This could probably sound silly, but my question is about arrays and their syntax:

Isn't redundant to declare an array with this syntax?

$data[] = array(
    'ct_id' => $row->ct_id,
    'association' => $row->association_name,
    'designation' => $row->designation_name,
    'license_number' => $row->license_number,
    'license_date' => $row->license_date ? date("jS F, Y", strtotime($row->license_date)) : '',
    'date_added' => date("jS F, Y", strtotime($row->date_added))
);

Should the declaration of the array be sufficient to define an array?

This code happens in a foreach loop like that:

foreach ($this->something->result() as $row) {..}

Upvotes: 0

Views: 162

Answers (2)

Kuldeep
Kuldeep

Reputation: 83

You should declared array without 【】

If you want a new element to add in array use 【】 like below,

$data【"test key"】= "test value";

So array() is for array initialization and 【】is for add new element.

Upvotes: 0

Liftoff
Liftoff

Reputation: 25392

There are two things going on here.

array(...)

is one syntax to define an array in PHP.

$data[] = ...

takes whatever is to the right of the equals sign and appends it to the array contained in $data.

So your result would look like:

$data => array(
    array(
        ...
    )
)

Upvotes: 4

Related Questions