PHP Associative Arrays Coding Style

No PHP programmer writes code without arrays. Sound strange, but as many programmers there are, as many ways to format the array notation there are.

My advice is to rely on a defined standard. I personally use the Zend Framework’s coding style.

So how to format the code? The first way is on the same line:

$myArray = array('key1' => 'value1',
		 'key2' => 'value2');

And the other, perhaps more clear way is to place the associative pairs on a new line:

$myArray = array(
	'key1' => 'value1',
	'key2' => 'value2',

Note that in the second example there’s a comma after the second pair. This is correct PHP syntax and is strongly encouraged!

It’s up to you which way to take. However it mainly depends on the case, but please use standards.

6 thoughts on “PHP Associative Arrays Coding Style

  1. I would argue about number 2 (ha ha). The problem come when you are working between PHP and JS. JS, you can’t have the extra comma for your “arrays”

    My formatting of arrays is like this

    $array = array('item1' => 'thing',
                   'house' => array('door'   => 'red',
                                    'window' => 'clear'
  2. “there’s a comma after the second pair. This is correct PHP syntax and is strongly encouraged”

    why it is encouraged ? is there any specific reason?

  3. @EllisGL – note that in JavaScript you don’t even use the => notation! So perhaps when you switch coding between PHP and JS there’s not only the last comma problem but the different syntax.
    However in JS it’s difficult to say which syntax is correct because only MSIE doesn’t accept the comma after the last pair. In other browsers the code’s parsed correctly with the comma.

  4. @Permana – Yes and that’s well described by ZF’s coding style here:

    When using this latter declaration, we encourage using a trailing comma for the last item in the array; this minimizes the impact of adding new items on successive lines, and helps to ensure no parse errors occur due to a missing comma.

  5. I feel like I’m constantly searching for intriguing issues to read about a variety of subjects, but I manage to incorporate your weblog among my reads every day because you’ve compelling entries that I appear forward to. Here’s hoping there’s a great deal far more remarkable material coming!

Leave a Reply

Your email address will not be published. Required fields are marked *