tags:

views:

254

answers:

8

What are the different ways of writing if conditional statements using PHP?

I know for example of the following

if($test == 1){
}else{
}

and

if($test == 1)
   echo 'asdsa';
else
   echo 'sdaaa';
+8  A: 

The other way is to use a ternary operator. The example in the PHP documentation is:

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}

?>

The other control structures are documented in the PHP manual as well. The only conditional statements are the ternary conditional operator, if (and else), and elseif or else if. However, they do have an alternative syntax.

Thomas Owens
And it's shorter
Roland
+2  A: 
if($test == 1){
}else{
}

# can only be used if performing 1 line of code after statement
if($test == 1)
   echo 'asdsa';
else
   echo 'sdaaa';

#you can have as many elseif as you like (but you may wish to check out switch see below:
if($test == 1){
}elseif{
}else{
}

Also take a look at switch() http://php.net/manual/en/control-structures.switch.php

switch($test)
{
    case "1" :
        break;
    case "2" :
        break;
    default :
        break;
}
Lizard
+9  A: 

There's the alternative control structure syntax:

if ($text == 1):
    echo 'asdsa';
else:
   echo 'asdsa';
endif;
Greg
This is useful to use in views (the V in MVC). It makes things slightly easier to read (you can tell exactly which control structure is closing etc).
alex
Heh. I just remembered the alternative control structure syntax and added that to my post. I haven't used it very often, since I usually write back-end (non-view) modules, but I have used it in views.
Thomas Owens
man, i hate this syntax. There's probably nothing actually wrong with it, but it reminds me of BASIC.
nickf
@nickf Oh BASIC was beautiful! ;)
alex
+1  A: 

Straight from the PHP manual:

<?php
if ($a == 5):
    echo "a equals 5";
    echo "...";
elseif ($a == 6):
    echo "a equals 6";
    echo "!!!";
else:
    echo "a is neither 5 nor 6";
endif;
?>
dnagirl
+4  A: 

Besides what's already been said, there's stuff like

$sql_link = mysql_connect('localhost', 'root') or die('no mysql');

Or like Alternative syntax for control structures

(the assignment "OR" trick is really a trick :) if the mysql_connect() doesn't evaulate to true, PHP will try to evaluate the second expression so this is really a hack of:

if (mysql_connect('localhost', 'root')) {
    $sql_link = true;
}
else {
    die('no mysql');
}

)

Tom
+1 I totally forgot about "or" in PHP .. never use it anymore but years ago it was all over my code.
MiRAGe
+3  A: 

Don't forget that "Conditional Complexity" is a code smell. Polymorphism is your friend.

Conditional logic is innocent in its infancy, when it’s simple to understand and contained within a few lines of code. Unfortunately, it rarely ages well. You implement several new features and suddenly your conditional logic becomes complicated and expansive. [Joshua Kerevsky: Refactoring to Patterns]

One of the simplest things you can do to avoid nested if blocks is to learn to use Guard Clauses. (Note: this is not PHP syntax. Regard it as pseudo code. The techniques here are what are important.)

double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
};

The other thing I have found simplifies things pretty well, and which makes your code self-documenting, is Consolidating conditionals.

double disabilityAmount() {
 if (isNotEligableForDisability()) return 0;
 // compute the disability amount

Other valuable refactoring techniques associated with conditional expressions include Decompose Conditional, Replace Conditional with Visitor, and Reverse Conditional.

Now that you have some new hammers, don't let everything look like a nail!

Ewan Todd
taking an early return (i.e. in the middle of a function) is what I call bad practice and very error prone. probably not in PHP, but if you use it in other languages you might end up leaking memory, etc.use a switch instead.
MiRAGe
p.s: using an early return in a switch is also bad. I just meant to simplify your code (and make it maintainable) by using a switch.
MiRAGe
@MiRAGe: You are reciting Dijkstra's SESE (single entry, single exit) dictum from "Structured Programming." See here for a discussion: http://msmvps.com/blogs/peterritchie/archive/2008/03/07/single-entry-single-exit-should-it-still-be-applicable-in-object-oriented-languages.aspx.
Ewan Todd
+5  A: 
echo ($test == 1) ? 'asdsa' : 'sdaaa';
Milan Babuškov
I was worried someone might forget this one. This is my favorite, because I'm not allowed to use it at work :D
MiRAGe
That’s not a statement, that’s just an expression.
Gumbo
That's not a planet...
nickf
+1  A: 

The standard if statement:

if(expression) {
    // code
} elseif(expression) {
    // code
} else {
    // code
}

Without braces for single lines of code after each statement:

if(expression)
    // single line of code
elseif(expression)
    // single line of code
else
    // single line of code

The alternate control syntax:

if(expression):
    // code
elseif(expression):
    // code
else:
    // code
endif;

And finally, the ternary operator:

(expression ? expression_if_true : expression_if_false);

Which can also be written as:

(expression) ? expression_if_true : expression_if_false;

Or without brackets entirely if you wish.

Nathan Kleyn