Why do PHP Array Examples Leave a Trailing Comma?

后端 未结 10 1582

I have seen examples like the following:

$data = array(
   \'username\' => $user->getUsername(),
   \'userpass\' => $user->getPassword(),
   \'em         


        
相关标签:
10条回答
  • 2020-12-05 09:38

    I've always added commas at the start of the new entry. Compilers see it as the single-character token of look-ahead that says "there is another one coming". I don't know if modern compilers use LR(1) (left-recursive, single token look-ahead) but I think that's where the syntax error originates when an a comma has nothing after it. It is rare that I've ever had another developer agree with me, but it looks like JohnBrooking does!

    0 讨论(0)
  • 2020-12-05 09:42

    The reason is commit changes.

    If you have to add the trailing comma when adding a new element. You're changing 1 line and adding 1 line. (-++)

    When adding a new element when a comma is already in the line above. There is only 1 added line, and no changed ones. (+)

    0 讨论(0)
  • 2020-12-05 09:42

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

    0 讨论(0)
  • 2020-12-05 09:45

    This surprised me recently, but it makes sense. I have long tried to adhere to an earlier convention that accomplishes the same thing, which is to put the separating comma in front of each entry rather than at the end.

    $data = array(
       'username' => $user->getUsername()
     , 'userpass' => $user->getPassword()
     , 'email' => $user->getEmail()
    );
    

    The commas also all line up that way, which looks nice, but it can make the indenting a little awkward. Maybe for that reason, it doesn't seem to have caught on much over the years, and I've had others ask me why I do it. I guess PHP's solution is a good compromise, and in any case, it's apparently the accepted solution now.

    0 讨论(0)
  • 2020-12-05 09:55

    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.

    0 讨论(0)
  • 2020-12-05 09:55

    I feel that even though it is allowed it is bad practice, its like leaving out the last semi colon of your functions and loops.

    0 讨论(0)
提交回复
热议问题