Married, moved, and getting it together.

Trailing commas in an array OK in PHP 2007 Jan 24

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.

blogged this at 9:52pm in 2007 in January. The 24th was a Wednesday. You are reading this 13 years later. Comment. There are 6 comments Tweet. Send email. It has hashtags→ .

Comments: 6

I know! Right?

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

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

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

Comments Open; Trackbacks Open.