Married,moved,and getting it together.

Trailing commas in an array OK in PHP

I was editing some code today and saw what looked like an error to me, but nothing was broken on the code I was looking at it, so I was prompted to look it up. And indeed, in PHP:

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

So sayeth the documentation for PHP: array
If it says it in there, it must be true.
So this is legal php:

… which, as I said, looks so bizarre to me.

six comments so far...

Looks like I’m late to the party, but the trailing comma is a rather handy feature. Sure it looks hideous in a one-liner array like in your example, but consider it in an array where each element of the array is long enough to deserve its own line. Now consider the event when you re-order some of those lines, and one of those lines is the last one. Now you need to add a comma to the formerly last element, and remove the comma from the new last element. If you use a trailing comma, you don’t need to worry about this.

Also, a syntax that allows trailing commas makes automatic source code generation easier.

You don’t realize how convenient this is?

I run into that in JavaScript all the time, when I am adding/removing elements from objects. If you leave a trailing comma on the last item, Firefox/Webkit are okay with it, but IE throws an error.

Python allows this, too. I’m sure many languages also do so.

And don’t you just hate the superfluous trailing ; before a } ?
if ( $n>10) {
++$x; // what's the stupid semicolon on this line good for?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.