views:

142

answers:

4

I've seen a lot of code recently formatted as the following:

A:

if ($var=='test'){
    $var=Foo('blah'.$var1);
}else{
    // do something
}

Personally I don't like it and would prefer it as:

B:

if ($var == 'test') {
    $var = Foo('blah' . $var1);
} else {
    // do something
}

I think it's much more readable (note the addition of spaces).

Is there a general preference in the community or is one way better than another.

+11  A: 

The most important thing is to follow a standard and stick to it.

That said maybe you can follow Zend's Framework standards and they use spaces. Check C.4.6.

if ($a != 2) {
    $a = 2;
}

Hope it helps!

Frankie
+1. Clear answer. Although it should be noted that whatever standard you go with, make sure it's clearly readable. In that aspect, Zend seems to do pretty well.
Duroth
Please take care to follow Zend in PHP, not C. Good god, those macros can make your head explode.
Tim Post
+3  A: 

+1 for spaces :)

but that's just my own standard, as long as you are consistent and your code is clear, it should be okay

Sylvain
+1  A: 

PHP is much like C in its syntax. As I use both, I tend to follow the same style.

For instance, keywords vs functions:

if ($foo) {

vs

MySuperDuperFunction($foo);

Then you come to a question of indentation:

switch ($bar) {
    case CONSTANT:
        more_code();

.. is much easier to read as

switch ($bar) {
case CONSTANT:
    more_code();

This indicates that the switch and the case are on the same level, which they are. It also helps avoid crazy indentation in yet-to-be-optimal switches.

Your style should illustrate the syntactic sugar of the language you are using. This gets strange with PHP as well as C, because both have forgiving parsers.

If you write something like this:

if($a==2&&b==1&&c>3)
{

I'm going to hunt you down and demand that you pay for my aspirin. The same would go for this:

if (
    a==2
     &&
    b==1
     &&
    c>3
)
{

... For God sakes man, its not LISP!

Tim Post
A: 

It's a matter of convetions that are stablished within your team.

The most famous conventions are Zend Framework and PEAR. You can also create your own, just make sure it is readible.

Personally, I use spaces.

Felipe Ribeiro