Should PHP code have spaces before operators?

658

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?

433

Answer

Solution:

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!

887

Answer

Solution:

+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

419

Answer

Solution:

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!

398

Answer

Solution:

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.

82

Answer

Solution:

The general advice would be to standardize the code formating, so it meets some best practices, and is widely known, instead of inventing something custom.

, the coding style guide would be the best well known approach, accepted by many. here are , why it's good to keep the code formatting.

People are also looking for solutions to the problem: Forming an Array and/or List within PHP from an html form POST that contains an unknown number of values that are initially arranged by JavaScript

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.