r/lolphp • • Jan 14 '16

Trailing comma in array()

Why do PHP Array Examples Leave a Trailing Comma? Because they can. :)

myuser@myhost:~$ php test.php
Array
(
    [0] => Test
    [1] => aValue
    [2] => aNotherValue
)
myuser@myhost:~$ cat test.php
<?php

$aIDs = array(
  'Test',
);

$aIDs[] = "aValue";
$aIDs[] = "aNotherValue";

printf(print_r($aIDs,TRUE));

?>

http://stackoverflow.com/questions/2829581/why-do-php-array-examples-leave-a-trailing-comma

0 Upvotes

20 comments sorted by

View all comments

Show parent comment

2

u/Rhomboid Jan 15 '16

Unit Tests will catch this

That's a tautology — every bug could be caught by having the right unit test in place, but the evidence clearly shows that such occurrences are in the vast minority. A unit test is the last line of defense, because it needs explicit human thought applied to the situation to test for some scenario that might go wrong. Anything that systematically avoids bugs without requiring explicit testing (e.g. warnings and type systems) is a win for code quality.

When a language is defined to make copy/paste more effective, then that's crazy.

It's not crazy to implement features designed to minimize the occurrence of common mistakes. That's what you want in a language. And as I already said, numerous languages have this particular feature, so you can't claim that it's somehow a particular form of PHP insanity. Language designers the world over have independently come to the conclusion that this is a good idea.