How to correctly format PHP 'IF ELSE' statements?
Asked Answered
E

12

7

It's been a long running issue that I've come across in many-a-hot-and-steamy coding sessions.

One person codes this way another codes that way. So after much push and pull I'm curious... Is there any correct way of phrasing a PHP 'IF ELSE' statement?

Personally I use the:

if ($variable == 'setvalue')
{
    $variable = executefunctiononvariable($variable);
} else {
    $variable = executedifferentfunctiononvariable($variable);
}

After many arguments though I've been presented with other options such as:

if ($variable == 'setvalue')
{
    $variable = executefunctiononvariable($variable);
}
else
{
    $variable = executedifferentfunctiononvariable($variable);
}

OR

if ($variable == 'setvalue')
    $variable = executefunctiononvariable($variable);
else
    $variable = executedifferentfunctiononvariable($variable);

OR

if ($variable == 'setvalue') {
    $variable = executefunctiononvariable($variable);
} else {
    $variable = executedifferentfunctiononvariable($variable);
}
Exergue answered 15/2, 2009 at 4:29 Comment(0)
B
22

I personally format my if/else like the last one:

if ($variable == 'setvalue') {
    $variable = executefunctiononvariable($variable);
} else {
    $variable = executedifferentfunctiononvariable($variable);
}

Your version is kind a mixture of 1 and 3, in my mind.

I have also worked with coders that do all of them and have never heard of a standard one.

The php website uses the last one: https://www.php.net/manual/en/control-structures.elseif.php

I also use the second example in some cases when the if statement will always be very short. If there's ever a possibiltiy of it getting longer (more than 1 line each) I'll do #1. I try to avoid #2 when possible cause it's hard to add the {} later.

Bonaventure answered 15/2, 2009 at 4:34 Comment(1)
The PHP.net manual uses the last method because we follow the PEAR coding standards. (pear.php.net/manual/en/standards.php) My personal favourite as well.Mccafferty
K
8

I use the last one:

if ($variable == 'setvalue') {
    $variable = executefunctiononvariable($variable);
} else {
    $variable = executedifferentfunctiononvariable($variable);
}    

That being said, it is pretty unimportant which one you go with, just make sure you are consistent.

Kitts answered 15/2, 2009 at 4:34 Comment(0)
S
7

The Right Way is to follow your project's coding standard. If you don't have one, adopt one from PHP-FIG, Zend, Symfony, etc.

This form appears very popular:

if (condition) {
    statements
} else {
    statements
}

For variable assignment I'll use a ternary only if the statement can fit legibly on one line:

$variable = !empty($foo) ? $foo : 'default';

Update: I've removed the bit about a multi-line ternary statements as I no longer consider this a wise practice.

Superload answered 15/2, 2009 at 4:55 Comment(8)
A problem I have with your use of ?: is that there may be side effects to those function calls. I did not see the assignment right away, either -- perhaps an indention to past the = would make it more apparent. Personally, I disagree with constants before variables in comparisons, as it makes ...Phyletic
... the code read unnaturally. "count($array) > $i" is harder to understand than "$i < count($array)", for example.Phyletic
@strager: You only put the literal on the left when it's checking for equality (==), as the whole point is to avoid accidental assignment (which can cause very odd bugs).Moira
@strager: no need to worry about side effects, the conditional operator does NOT execute both the two options; it's operationally identical to the if/else.Superload
I personally only use the "? : " when the entire statement easily fits on 1 line. Anything larger/complex becomes an "if" for readabilityDusk
I would wrap that whole thing in an extra set of brackets. It looks like $variable is getting assigned a boolean value, not the return of one of those functions. That said, I'm still not overly found of it, and I hate your "literal on the left" thing. I understand it's to prevent bugs, but readability is more important to me. Any bug caused by forgetting an = (or two in this case!) is usually immediately obvious... or maybe not in this case, because you made it so darn compact, that if you screwed it up it would always evaluate to true, and then take the first function.Trickster
i've never seen multi-line ternary formatted like that but it's kinda nice :-) i don't exactly see the benefit but it's good to see something which is clean, readable and not like what i already do.Machismo
Not shockingly, six years later I no longer create multiline ternary assignments. If/else is not only more readable, but also makes git diffs more readable when you alter it.Superload
S
4

I personnally prefer:

if(something){
    doSomething();
}
elseif(somethingElse){
    doSomethingElse();
}
else{
    doAnotherThing();
}
Spaetzle answered 15/2, 2009 at 10:10 Comment(4)
There is no "correct" way, and this is the ugliest of all of them. Why? You're creating extra space by leaving the closing brace on its own line as if to give it some added visual separation, but then you nudge the if statement against the code block anyway. It looks like an inconsistent mess to me. And the lack of a space after your else statements also bothers me :DTrickster
Agreed with Mark. I don't like this way.Lettie
actually, I switched to mrclay's method since writing this answer (his first code block, not the second) And now two think this is ugly.Spaetzle
The problem with this is the spacing, not the extra linefeed after the block close. Having the extra linefeed means that the elsif and else line up directly below the if. That looks most correct to me, as opposed to doing } else {, which means the else is indented two spaces. But yeah, the lack of spaces before the tests and the open block is horrible.Aleron
L
4

Don't forget about

if (expression):
   // code goes here
elseif (another expression):
   // code goes here
else:
   // code goes here
endif;

I personally like this structure when I'm cooking some tag soup.

Litigable answered 14/5, 2009 at 20:10 Comment(1)
I only like this if you're tossing HTML inbetween.Trickster
G
3

The most important thing is that the programmers working on a project pretty much adhere to the same coding guidelines. So have a meeting and pick one or the other, and then stick with it.

Geochronology answered 15/2, 2009 at 4:34 Comment(0)
A
3

I used to do (2) all the time but got it beaten out of me from Java programming as Sun's coding conventions use (4). So now I'm pretty used to (4). I've been doing a bit of C# lately and it seems to use (2) by default (sigh, here we go again).

In PHP from habit I do (4) but (2) is fine too. I don't like (1) at all.

And (3) is dangerous. Personally I think braces should be required by the syntax of the langauge even if its just for one statement. Saves you getting into trouble. I think that's how Perl does it from memory.

What I also hate is when people do this:

if (something) {
  // do something
}
else if (something else) {
}

That one drives me batty. So I only find (2) and (4) acceptable. I don't care which one it is, as long as it's done consistently, preferably within the conventions for the language.

Aschim answered 15/2, 2009 at 5:15 Comment(1)
Why does it drive you batty? It's the most logical way to write it. Using } else { means it doesn't line up under the if, which is just weird in my opinion.Aleron
H
2

There is no right or wrong way, it is an opinion. Personally, I like the last one best (1TBS???). I never use the one without braces, I consider it bad style in general.

The only people that can really answer this question for you are the other people that are going to work on the code. It is important that everone agrees to a coding standard. Which standard you choose is less important than the fact that everyone uses it.

Hugues answered 15/2, 2009 at 4:37 Comment(0)
M
2

The PEAR coding standard is the PHP coding standard. I would recommend to get used to it as you will find it in other projects such as Zend, Doctrine, Symfony, Horde and many, many more.

http://framework.zend.com/manual/en/coding-standard.coding-style.html#coding-standard.coding-style.control-statements.if-else-elseif

Mathison answered 15/2, 2009 at 5:15 Comment(1)
At least someone mentioned that there already is a coding standard.Etienne
O
1

In short, the is no correct way of doing. As long as it works, whatever you feel is the best, you can use. You should pick one and then stick to it, it will make your code easier to recognise.

The only thing is, if you don't include the "{" character you are limited to one expression or function.

Also, if you are only looking to define variables you can use the following code:

$variable = (CONDITIONAL STATEMENT) ? "It was true" : "It was false"; 
Omnipotent answered 15/2, 2009 at 4:32 Comment(0)
C
0

At my company we use:

if ($variable == 'setvalue')
{
    $variable = executefunctiononvariable($variable);
}
else
{
    $variable = executedifferentfunctiononvariable($variable);
}

I doesn't really matter aslong as there is a standard

Custer answered 15/2, 2009 at 10:27 Comment(0)
P
0

Really to me... it just doesn't matter. I believe you should be able to read either way without issues. Does it really matter if the curly brace is on a new line or not? Does it really matter if there's a space after the closing parenthesis or not?

As long as the code is done in a such way that there's been at least an attempt at making it readable, I really just don't care.

Is there a correct way? Well if there was, then why do we have options of doing it differently?

Pittsburgh answered 5/8, 2009 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.