Do you use a lot of if else statements? Do you ever wish there was a quicker way of using them without taking up several lines of code? Well, there is and I’m using today’s tutorial to explain how to do it using Ternary Operators.
Just a quick note first about my gaming post over the weekend: That post went down very well so I’ll be looking to do more similar articles over the next few weeks.
In the meantime I’ll be doing short mid-week PHP tutorials rather than more complicated tutorials like the CodeIgniter tutorial I did on Database Migrations.
Traditional If Statement
A normal if else statement checking whether a value exists (good practice to avoid notices) might look something like this:
$data = $_POST['data'];
$data = 'empty';
This is a basic assignment example where $data is being set to the post variable or if it’s not set then it’ll set $data to the word ‘empty’.
Shorthand If..Else using Ternary Operators (?:)
That will work fine but it also takes up quite a few lines (especially if you need to do it multiple times) when you can do the exact same thing with much less code.
The format to use when using Ternary Operators is (condition ? true result : false result) – For example:
$data = (isset($_POST['data']) ? $_POST['data'] : 'empty');
This will produce the exact same outcome as the previous code example. If the condition is met then in this case $data will be set to $_POST['data'] otherwise it will be set to the word ‘empty’.
This can also be used in the same way when echoing data:
echo ($foobar == true ? "foo" : "bar");
Or in the middle of an assignment / echo:
echo "Hello ".($username == "Robert" ? "Super " : "Loser ").$username;
Nested Shorthand If
If need-be you can also nest these shorthand statements as well:
$data = (isset($_POST['data']) ? $_POST['data'] : (isset($_GET['data']) ? $_GET['data'] : 'empty') );
There is a slightly different way of doing shorthand if statements which I have included below:
$data = (isset($_POST['data'])) ? $_POST['data'] : ‘empty’;
The difference as you can see is that the if bracket is closed straight after the condition. Both methods will work with nesting so it’s simply down to developer preference. I prefer the first method I provided as I think it would be easier to debug the nestings (as many IDE’s will highlight the bracket pairings).
So there you have it, there are plenty of ways of using shorthand if else statements to your advantage. It helps reduce the amount of code that you need to write without losing any readability. This only works with singular commands though, so if you need to do more than one command in an if statement then you’re best off sticking to the traditional way of doing it.
Got any other tips you’d like to see me share? Get in Touch and let me know!