PHP Shortcuts Episode 2: The ternary operator

The ternary operator in PHP is basically a shorthand way of writing conditional statements, for which we would usually use the familiar if and else etc.

For example, in a program that decides what I’m going to do in my lunch hour:

if($is_friday) {
     $activity = 'go to the pub';
} else {
     $activity = 'stay at work';

We could write this with less code (less code is better, right?)

$activity = $is_friday ? 'go to the pub' : 'stay at work';

So, what happens here is if $is_friday equates to TRUE, the value after the question mark (‘go to the pub’) is assigned to the variable $activity. If $is_friday equates to FALSE then the value after the semi-colon (‘stay at work’) is assigned to $activity instead.

The other neat thing about the ternary operator is we can use it as part of an echo statement to decide what we’re doing and output it to the page in one easy line of code like so:

It's my lunch hour and today I'm going to <?php echo $is_friday ? 'go to the pub' : 'stay at work'; ?>.

Hooray for ternary operators, unfortunately it’s Thursday today so I’ll be staying at work!

PHP Shortcuts Episode 1: Simple form/query string values

Hello and welcome to my new mini blog series on PHP shortcuts. I’ll be posting some handy code snippets that I’ve used over the years that will save you both time and possibly also from Repetitive Strain Injury!

First off – A quick function to get a value from both the $_GET or $_POST arrays without potentially throwing errors by forgetting to check if your particular array key exists before trying to access it.

The old, long-winded way:

if(isset($_GET['first_name'])) {
     $first_name = $_GET['first_name'];
} else if(isset($_POST['first_name'])) {
     $first_name = $_POST['first_name'];
} else {
     $first_name = NULL;

if(isset($_GET['last_name'])) {
     $last_name = $_GET['last_name'];
} else if(isset($_POST['last_name'])) {
     $last_name = $_POST['last_name'];
} else {
     $last_name = NULL;

The new, super-quick and easy way:

function get_post($p) {
     if(isset($_GET[$p])) {
          return $_GET[$p];
     } else if(isset($_POST[$p])) {
          return $_POST[$p];
     } else {
          return NULL;

$first_name = get_post('first_name');
$last_name = get_post('last_name');

Job done! See you next time.