Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do PHP Array Examples Leave a Trailing Comma?

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.

like image 801
ashurexm Avatar asked May 13 '10 19:05

ashurexm


4 Answers

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.

like image 173
Pekka Avatar answered Oct 22 '22 21:10

Pekka


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.

like image 33
Janci Avatar answered Oct 22 '22 20:10

Janci


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.

like image 29
user985366 Avatar answered Oct 22 '22 21:10

user985366


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.

like image 10
ahnbizcad Avatar answered Oct 22 '22 20:10

ahnbizcad