Getting Your Projects Done Faster by Writing Less Code with the Short-hand if()

Have you coded a simple if() construct that sets a variable to one of two values and thought to yourself "Five lines of code; there should be a better way?" Okay, maybe it's just me. Either way, let's take a look at the Ternary Operator [aka the short-hand if()].


Let's say we're processing some data from an HTML form and come across a checkbox value. The value could be utilized as is, but maybe we don't want to insert the word "on" into our database when the field is checked. Beside, who knows what that checkbox value could contain; it might be something shady. Well the following code could be used to set the checkbox value to one (1 – true) or zero (0 – false):

if($_POST['checkbox_value1']) {
     $checkbox_value1 = 1;
} else {
     $checkbox_value1 = 0;

Alternate Format

However, the standard if() construct above can be a little difficult to manage, especially if there are a lot of checkboxes to validate. We could condense the code so that the entire if/else construct appears on the same line for each checkbox. But let's go even further with the Ternary Operator:

$checkbox_value1 = ($_POST['checkbox_value1']) ? 1 : 0;

Now that's a very compact chunk of code which is easy to scan. Once you get used to the new format, that is.

Related Posts


There are currently no comments.

Leave a Comment