Using PHP's alternate syntaxes

If you’ve ever worked with PHP you’ll be more than familiar with the use of if/elseif/else conditional statements, these statements often become large and unweildy, especially when HTML is mixed in with PHP, causing a problems with code readability. There are a couple of alternate ways to write these statements which can improve your code.

if..endif syntax

We’ll start with a simple example of a ‘regular’ statement which includes a foreach and an if statement which is extremely common among PHP scripts.

1
2
3
4
5
6
7
8
9

foreach($array_expressionas$value){
    if($expression1){
        echo'Result1';
    }else{
        echo'Result2';
    }
}
?>
Now, just for funzies, let’s make this a tiny bit more complex and mix in some HTML markup in there for good measure, just like you’d see in, say, a WordPress template where we’re jumping back and forth between HTML and PHP mode.

1
2
3
4
5
6
7
8
9
10
11

foreach($array_expressionas$value){
    if($expression1){
?>
       

Result1


 }else{?>
       

Result2



    }
}
?>
See the closing braces on lines 9 & 10? With a relatively small example like this you can scan back through the code to see wether they close the if or the elseif. Now imagine a much larger statement, the only way to find out what the closing brace actually closes is to either pay attention to the tab levels (providing the tab levels have been maintained properly), or to read back through the whole statement and match them up. There is an alternate syntax which makes life a little easier.

Alternate syntax

By using the alternate if..elseif syntax we can replace those closing braces with something a little more useful.

1
2
3
4
5
6
7
8
9
10
11

foreach($array_expressionas$value):
    if($expression1):
?>
       

Result1


 else:?>
       

Result2



    endif;
endforeach;
?>
This alternate syntax is expecially useful when mixing PHP and HTML and works for if/while/for control structures.

Ternary operator

For simple evaluations you can use the ternary operator which is a slimline version of an if/else statement, for example, the following statement which pluralises a string based on an integer variable.

1
2
3
4
5
6
7
8

if($count1){
    $comments='comment';
}else{
    $comments='comments';
}
echo$count.' '.$comments;
?>
#### Alternate syntax

Using the ternary operator this can be condensed to a single line:

1
2
3
4

$comments=($count1) ? 'comment':'comments';
echo$count.' '.$comments;
?>
### Have a try!

By learning and adopting these alternate syntaxes you will ensure that your code remains readable and maintainable, especially if you’re writing code to be used by other people. Give them a try!

comments powered by Disqus