CyberJunkie
CyberJunkie

Reputation: 22674

No comma after last element in array?

I noticed that some arrays don't have a comma after the last item. I have an array:

$first_name = array(
              'name'        => 'first_name',
              'id'          => 'first_name',
              'maxlength'   => '20',             
              'class'       => 'text',
              'placeholder' => 'First name',
            );

I have a comma but no php errors. Should I keep or remove the comma?

Upvotes: 17

Views: 6813

Answers (4)

Michas
Michas

Reputation: 9438

The comma after last element may not work in every language. However it make diffs in version control systems cleaner for supported languages.

/* From */
$a = array(
    'element_w',
    'element_x',
);
/* To */
$a = array(
    'element_w',
    'element_x',
    'element_y', /* Only this line will show in version control. */
);


/* From */
$a = array(
    'element_w',
    'element_x'
);
/* To */
$a = array(
    'element_w',
    'element_x', /* These two lines               */
    'element_y'  /* will show in version control. */
);

Upvotes: 6

Michael Berkowski
Michael Berkowski

Reputation: 270637

It is a style preference as mentioned elsewhere, however I would advise to condition yourself against adding that trailing comma in PHP, as it is syntactically invalid in some languages. In particular, I'm thinking of Internet Explorer's handling of those types of trailing commas in Javascript, which are notoriously difficult bugs to locate when scripts fail in IE while succeeding everywhere else. It will also break JSON's validity, and is invalid in a SQL SELECT list, among other potential problems.

Again, it's a matter of preference, but could cause you problems in other areas.

Upvotes: 15

judda
judda

Reputation: 3972

Both are syntactically correct in a number of languages. The last element is ignored if left blank. It is a nice little easter egg built into languages just so you don't have to keep adding in , before you start modifying an array if you manually have to add a few more values in.

Upvotes: 5

jglouie
jglouie

Reputation: 12880

Sounds like a style preference if both are syntactically correct

Upvotes: 2

Related Questions