Married, moved, and getting it together.


January 24th, 2007

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.


Comments: 6

Sassy

January 25, 2007 7:14am

gross!

Joe Crawford

January 25, 2007 11:27am

I know! Right?

I guess they classify this stuff as “syntactic sugar” — but it just looks ugly/lazy to me!

Sassy

January 26, 2007 8:21am

what is the value of the last element? An empty string. Syntactic sugar my foot

Razalhague

November 18, 2009 5:51am

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.

Jerry

June 23, 2010 5:13pm

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.

tom

January 3, 2011 1:22pm

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

Leave a Reply