Best practice for using the PHP 5.3 Ternary operator

The Ternary Operator is very useful for short expressions.
I use it as sample very often to check GET or POST Variables, and give them in empty-cases a default-value.

Instead of making an examination of variables in an if statement, which is a lot of typing…

if(empty($_POST['action'])) {
    $varToUse = 'varIsEmpty';
else {
    $varToUse = $_GET['varToUse'];

You can do the same with a Ternary Operator, with a much less of typing:

$varToUse = (!empty($_GET['varToUse'])) ? $_GET['varToUse'] : "varIsEmpty";

Since PHP 5.3 it is possible, to do this even faster. Just leave out the middle part of the ternary operator, as sample:

$varIsEmpty = (empty($_GET['varToUse'])) ?: false;

So you can save a much of typing, to take a simple check 😉

  1. No comments yet.

  1. No trackbacks yet.