Andreas Rydberg

Home

PHP best practice tip: commas in arrays

Andreas — Sat, 2009-01-10 03:18

Something I discovered by accident. The array() constructor allows a comma (,) after the last item. This helps me and saves me time by avoiding bugs. I'll show you...

I did a quick look on PHP.net about arrays but couldn't find any mentions of this.

When developing, I often make arrays that looks like this:

<?php
// Example 1
$simpsons = array(
   
'Homer',
   
'Lisa',
   
'Bart',
   
'Maggie',
   
'Marge'
);
?>

I could have written them on one line - it works equally good. I usually write arrays this way because I think it's more readable.

Well, this is all fine and dandy! But sometimes i want to change the order for some reason, like putting the Simpson parents names together.

<?php
// Example 2
$simpsons = array(
   
'Homer',
   
'Marge'    // moved
   
'Lisa',
   
'Bart',
   
'Maggie',
);
?>

Now I moved "Marge" up, from last line to the second line. This won't run. Do you see the error?

The error is that I forgot to add a comma after "Marge". Notice also that I left the comma on the last line after "Maggie".

<?php
// Example 3
$simpsons = array(
   
'Homer',
   
'Marge',    // fixed, added a comma (,)
   
'Lisa',
   
'Bart',
   
'Maggie',    // left as is, PHP allows an extra comma (,) on the last line
);
?>

OK, now it's all well again. There is one more perk. When you copy and paste a line to add a new item, you don't need to go back and add a comma.

<?php
// Example 4
$simpsons = array(
   
'Homer',
   
'Marge',
   
'Lisa',
   
'Bart',
   
'Maggie',
   
'Grandpa',    // added a line by copying "Maggie"
);
?>

This work on associative arrays and arrays with numeric indices as well.

An interesting thing is when using the var_export-function, it will return an array with the comma on the last line. No matter how you created the array. Check out "Example #1" on PHP's page for var_export.

Summary

The pros are:

  • less error prone
  • easier to maintain

I can't really come up with any cons. If you have any, please leave a comment.

  • PHP

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <em> <strong> <cite> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

More information about formatting options

Blog posts

2011.12.16
Appland launched
2011.12.09
Learning Java, again - part 1
2011.11.20
Installing Lighttpd on Ubuntu 11.10
2011.03.15
New job and Aegir
2010.11.16
Acquia Drupal stack installer
  •  
  • 1 of 3
  • ››
Syndicate content

Powered by Drupal, an open source content management system