Skip to content
Advertisement

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement