views:

141

answers:

3

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.

+5  A: 

Why do PHP Array Examples Leave a Trailing Comma?

Because they can. :)

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. Firefox will leniently tolerate trailing commas; Internet Explorer will, rightly, throw an error.

Pekka
@Pekka: 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.
manyxcxi
@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.
Pekka
Newer versions of JavaScript than IE6/7 code for explicitly permit it, now.
staticsan
A: 

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.

Pheter
A: 

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

Kirzilla