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:

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

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

1
2
3
4
$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.

Related posts:

  1. JavaScript Objects Coding Style Reviewed
  2. PHP Coding Style: Large IF Statements
  3. JavaScript Objects Coding Style
This entry was posted in micro tutorial, PHP and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

5 Responses to PHP Associative Arrays Coding Style

  1. EllisGL says:

    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

    1
    2
    3
    4
    5
    
    $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. Stoimen says:

    @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. Stoimen says:

    @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. EllisGL says:

    @Stoimen: You are correct about that. Doh!

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">