Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No comma after last element in array?

Tags:

arrays

php

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?

like image 746
CyberJunkie Avatar asked May 27 '11 00:05

CyberJunkie


People also ask

How do you remove the comma at the end of an array?

You can use the join() method in JavaScript to remove commas from an array. The comma delimiter in an array works as the separator.

How do I get an array without the last element?

Using the Array pop() Method The Array pop() method is the simplest method used to remove the last element in an array. The pop() method returns the removed element from the original array.

Can trailing commas be used in objects and arrays?

JavaScript has allowed trailing commas in array literals since the beginning. Trailing commas are now also allowed in object literals, function parameters, named imports, named exports, and more.


1 Answers

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.

like image 109
Michael Berkowski Avatar answered Sep 22 '22 18:09

Michael Berkowski