Why do PHP Array Examples Leave a Trailing Comma?
Asked Answered
E

11

97

I have seen examples like the following:

$data = array(
   'username' => $user->getUsername(),
   'userpass' => $user->getPassword(),
   'email' => $user->getEmail(),
);

However, in practice I have always not left the trailing comma. Am I doing something wrong, or is this just 'another' way of doing it? If I was using a framework would not having the trailing comma affect code generation negatively? I have seen the use of trailing commas in array declarations in other languages (Java, C++) as well, so I assume the reasons for leaving trailing commas are not specific to PHP, but this has piqued my interest.

Eakins answered 13/5, 2010 at 19:13 Comment(3)
I could have sworn I was getting parse errors when I left training commas in PHP.Cogswell
It's possible, I guess. In this particular example it parses just fine.Eakins
Yeah @LotusNotes I'm sure I've had errors before too. But clearly, not anymore!Giddy
L
124

Why do PHP Array Examples Leave a Trailing Comma?

Because they can. :) The PHP Manual entry for array states:

Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.

Seriously, this is entirely for convenience so you can easily add another element to the array without having to first add the trailing comma to the last entry.

Speaking of other languages: Be careful with this in JavaScript. Some older browsers will throw an error, though newer ones generally allow it.

Lathrope answered 13/5, 2010 at 19:15 Comment(16)
This is what I figured, I just wasn't sure if I was missing the boat on something. I guess for people who spend their time in a few languages that allow this, it's probably a decent habit. But given that I deal with a lot of different languages, and as you said JavaScript (and who knows what other languages) could throw errors, it might be safer for me to continue my habit of not leaving a trailing comma.Eakins
@manyx yup, nothing wrong with that. I'm not sure either whether being able to keep trailing commas is a good thing. It looks like a syntax error when reviewing code.Lathrope
Newer versions of JavaScript than IE6/7 code for explicitly permit it, now.Dampproof
@Lathrope And convenience for removing in addition to adding an entry to the arrayNarrowminded
By the way, Python is another language that deliberately allows a trailing comma for ease of adding more entries. I wish JavaScript hadZendavesta
Perl also allows the trailing comma, and I believe it's encouraged. It's actually pretty nice to have when sharing code between developers using source control. If you want to add a line to the end and you need to add a comma, that means you're touching both lines. A git blame (or equivalent in other source control) will show that you wrote that line even though you just added a comma to it. Not a huge deal either way but handy.Weatherwise
I do admit though, when you're writing Javascript code it sucks to have that habit of leaving in extra comments. Although, who really cares about IE anyway? ;)Weatherwise
It's useful if you have files under source-control to keep the number of changed lines low.Deel
JSON too, JSON hates trailing commas.Rinna
Lua also allows a trailing comma and this is encouraged for consistency of array item and ease of writing.Responsum
I think the comment of @Weatherwise about git blame is the major reason I would do it. Maybe a good addition to the original answer.Skyscraper
I don't think newer versions of Internet Explorer reject trailing comma.Seoul
FWIW, I've had an instance where json_encode() failed to encode a final array element (a text string) where the trailing comma was omitted - it simply emitted an empty string. I had to insert the trailing comma before json_encode() would emit the actual array element.Hefty
It's not "entirely for convenience". It also prevents needless diff noise in version control systems when adding a new line.Friary
To answer an even deeper level of the "why", i.e. why the PHP developers would allow this, it is because, other than portability issues when converting code to other languages, there are no downsides of it, and there is the very real advantage that you can delete the last entry in a list where the comma occurs on the end of each line, and it results in valid syntax.Enchain
Just some more refs: Documented in this form since ca. Aug 2004, the syntax is older, albeit I don't know when it was introduced. For standard function call syntax trailing comma is possible since PHP 7.3, ref: Trailing Commas are allowed in Calls - New Features PHP 7.3Deel
C
32

I noticed when working with version control (git) that if we add 1 thing to an array and we don't have the trailing comma, it will look like we modified 2 lines because the comma had to be added to the previous line. I find this looks bad and can be misleading when looking at the file changes, and for this reason I think a trailing comma is a good thing.

Chops answered 22/2, 2016 at 10:22 Comment(7)
And that is, definitely, why trailing commas are for :) Diff consistencyArrio
I don't know if it has anything to do with why it's there. I would think not. But I find it useful.Chops
But that is the reason why it's here. One could say it's here to prevent mistakes on next line add. But it's not, because no IDE nowaday would let you add lines without comme, it would pop an error notice.Arrio
@Arrio Interesting. I took your first comment as being ironic, but I wasn't sure.Chops
Sorry, it may have looked ironical. It was very serious. We add commas on last array line to help versioning diffs being clean.Arrio
This is the best reason for using a trailing comma.Salesin
Extra info: Because of the problem described by @user985366, Symfony actually enforces trailing commas in their coding standards. symfony.com/doc/current/contributing/code/standards.htmlPatella
L
31

This is a good practice when defining array on multiple lines. It's also encouraged by ZendFramework's coding standards:

When using this latter declaration, we encourage using a trailing comma for the last item in the array; this minimizes the impact of adding new items on successive lines, and helps to ensure no parse errors occur due to a missing comma.

Lubricous answered 31/1, 2011 at 12:32 Comment(0)
B
11

Because it keeps entries uniform.

If you've had to swap the order, or add or delete entries, you know being able to leave a trailing comma is very convenient.

If the last element cannot have a comma, then you end up having to maintain the last comma by modifying entries. It's a pointless exercise and a waste of time and finger strokes because the intent of swapping or modifying entries is already accomplished.

By allowing a trailing comma on the last element, it frees the programmer from having to tend to this annoying and fruitless detail.

Bitten answered 27/1, 2016 at 0:36 Comment(0)
H
9

The reason is commit changes.

If you have to add the trailing comma when adding a new element. You're changing 1 line and adding 1 line. (-++)

When adding a new element when a comma is already in the line above. There is only 1 added line, and no changed ones. (+)

Hewett answered 23/11, 2018 at 13:7 Comment(0)
C
5

I can't speak for other people, but I usually leave a trailing comma in my code. I do so because if/when I later add to the array, I do not have to worry about missing out a comma due to forgetting to add a comma to what was previously the last line.

Cornfield answered 13/5, 2010 at 19:16 Comment(0)
D
3

I'm always doing trailing comma because it helps to avoid syntax errors while adding new array elements... it's just a good practice.

Durwood answered 13/5, 2010 at 19:17 Comment(2)
I'm sorry for reviving this but, how does a trailing comma prevent syntax errors later on? I've just found out that PHP allows for the trailing comma - but I cannot see/find the use for it. Adding new indexes later on is still done through $arr[] = ....Ergograph
@Daniel, he's talking about returning to the source code later and adding another line to the array literal.Prophetic
H
2

I feel that even though it is allowed it is bad practice, its like leaving out the last semi colon of your functions and loops.

Hafler answered 26/10, 2011 at 14:39 Comment(0)
R
1

If you look at an example of roundcube file config (config.inc.php), they have example with and without trailing comma.

This array defines what plugins should be enabled or disabled:

...
// List of active plugins (in plugins/ directory)
$config['plugins'] = array(
'managesieve',
'password',
'archive',
'zipdownload',
);
...

Normally, this would be line by line and if somebody wants to add something on the array, they can do this:

...
// List of active plugins (in plugins/ directory)
$config['plugins'] = array(
'managesieve', //code by personA
'password', //code by personA
'archive', //code by personA
'zipdownload', //code by personA
'newplugin', //new code by personB
);
...

So, when they commit this code, they see only one changes for that particular line and this is more readable when inspecting who is making the code changes for that particular line.

In another line of code you can see this without trailing comma:

...
$config['default_folders'] = array('INBOX', 'Drafts', 'Sent', 'INBOX.spam', 'Trash');
...

Normally it would be a single line of code where nobody expects this code to be changed frequently.

In another word:

1) Put trailing comma if the array is used as an option or configuration file that might need to be changed dynamically in the future. Besides, if you make changes to that array programmatically using trailing comma you only make changes to one line code, whereas without it, you have to deal with 2 line of codes and this can cause more complexity to parse the array

2) You don't have to put trailing comma if the array is a constant array and you don't expect it to change in the future but as mentioned by the Accepted Answer, you can put trailing comma but it has no purpose

Reform answered 31/12, 2020 at 15:18 Comment(0)
G
0

This surprised me recently, but it makes sense. I have long tried to adhere to an earlier convention that accomplishes the same thing, which is to put the separating comma in front of each entry rather than at the end.

$data = array(
   'username' => $user->getUsername()
 , 'userpass' => $user->getPassword()
 , 'email' => $user->getEmail()
);

The commas also all line up that way, which looks nice, but it can make the indenting a little awkward. Maybe for that reason, it doesn't seem to have caught on much over the years, and I've had others ask me why I do it. I guess PHP's solution is a good compromise, and in any case, it's apparently the accepted solution now.

Garay answered 11/4, 2019 at 16:47 Comment(0)
A
0

I've always added commas at the start of the new entry. Compilers see it as the single-character token of look-ahead that says "there is another one coming". I don't know if modern compilers use LR(1) (left-recursive, single token look-ahead) but I think that's where the syntax error originates when an a comma has nothing after it. It is rare that I've ever had another developer agree with me, but it looks like JohnBrooking does!

Adala answered 5/6, 2019 at 0:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.