PHP Shorthand if and else assignments

This entry was originally posted at Bird & Co Creative Design

What you don’t hear as a beginner

When you are learning a scripting language such as PHP you will get the basics of assignment, evaluating and comparison operators such as == <= and != (equal, less than or equal, not equal). They are all you need to start writing code that can vary it’s behaviour according to what inputs it is given. Before long though you will want quicker ways of doing things. In this blog post I’m going to start with the long way of doing assignments and then show you a much quicker way of doing it.

Assignments – The Long way round

When writing code, you will quite often want to assign a value to a variable based on a condition. For example..

//Make the variable $today hold the value Thursday
$today = "Thursday";
 
//Test if the variable $today is Friday,
//if it is then we can go to the pub for lunch
 
if($today == "Friday"){
 $goToThePubForLunch = true;
} else {
 $goToThePubForLunch = false;
}
 
//returns false. We aren't going to the pub today :(

This does the job, but takes up more space that it really needs to. We have a variable duplicated and have used 5 lines when really 1 should do. It would be great to shorten it and make our code more readable.

The Answer – ?:

This is where the Ternary operator “?:” comes in.

The pseudocode for the ternary operator is (expr1) ? (expr2) : (expr3) which basically means “if expression 1 is true, then return expression2 and if expression1 is false return expression3. (An expression can be thought of as anything that has a value)

In the case of our first example expression1 would be

$today == "Friday"

expression2 would be true
and expression3 would be false

So we can rewrite the above as

$today = "Thursday";
 
$goToThePubForLunch = ($today == "Friday" ? true : false);
//Returns false

This is much quicker and after using it a few times becomes as readable as the first version

Can we make it shorter?

Of course we can!

In the above example we are returning what is called a boolean variable. It is either true or false.

The comparison operators we are used to using such as “==” or “!=” return a boolean value when they are evaluated. By using that fact we can shorten the code to

$today = "Thursday";
 
$goToThePubForLunch = $today == "Friday";
//$today == "Friday" returns false
//which is then assigned to $goToThePubForLunch

Why use ternary operators then?

Well, remember that ternary operators allow us to evaluate any expression? We can increase what we can do with 1 line by putting a function call or a variable with something other than a boolean value in expression2 or 3

$today = "Friday";
 
$whereAreWeHavingLunch = ($today == "Friday" ? getRandomPub() : "In The Office");
//returns a random pub near by

Here we have added a function that chooses a pub to have lunch at. It only gets called if today is friday otherwise we just have lunch “in the office”.

There you go, a couple of quick ways to condense if else statements. For more info on ternary operators you can go to the php documentation site
http://php.net/manual/en/language.operators.comparison.php

4 Comments

  1. Derick says:

    Hi,

    first of all I disagree that you can only go to pubs on Friday’s, but secondly (and more seriously), writing PHP code (or actually any code) isn’t always about writing code in the least amount of keystrokes. It’s just as important to write *maintainable code*. The ternary operator isn’t always the best possible choice to write readable code, especially not when you nest them.

    Derick

    • Nick says:

      Hi Derick,

      Thanks for your comment, and I agree completely on maintainable readable code.

      The point of the post was more one of introducing people to the ternary operator and a few ways of using it. I have spoken to quite a lot of developers who simply don’t know what it is!
      They are silly examples precisely because you wouldn’t want to use them… of course we can go to the pub on other days!

  2. Tom says:

    Hi,

    Nice topic. I come from a Perl background, where the less code you write the smarter you are – or at least I think that’s the general way it works! Lol

    I’ve only just started using ternary operators in my PHP code though, but I think they’re great.

    I also think that if they are used sensibly, they don’t have to make the code any less maintainable. I’m a bit OCD when it comes to making code look pretty, and sometimes I think having less lines to scroll through actually makes your code easier and quicker to understand – it just takes a little getting used to, but once you’re happy with the syntax it’s fine.

    Tom

  3. Chad Huntley says:

    I’ve found a good use for the ternary operator is when writing small conditional statements inline with HTML.

    For example, if you want to add a class to a DIV when a certain condition is true. While still making things readable you can put a short snippet of PHP code within the class area to echo a new class. Not exactly A+ coding, but its a good quick way to get the job done.

Leave a Reply




Latest