in PHP

Shorthand Comparisons In PHP

In this tutorial we're going to investigate how we can improve our code by cleaning up unnecessary code by using shorthand code samples in PHP. So what do I mean by removing unnecessary code? The most common situation where you see unnecessary code is in the use of if statements which will force a return. For example you might have a situation where if the variable is true you return on thing and if the variable is false you'll return something different. Which will leave you with something like this.

function ifStatementReturn($value) {
    if($value) {
        return 'this value is true';
    } else {
        return 'this value is false';
    }
}

Let's investigate what we can do to clean up this code. First we don't need the else in this if statement as we're not doing anything after this if statement that relies on a variable to be change within this if statement therefore this can be remove.


function ifStatementReturn($value) {
    if($value) {
        return 'this value is true';
    } 

    return 'this value is false';
}

That's cleaner already but we can do more to clean up this code. We can use the ternary operator to remove this if statement completely.


function ifStatementReturn($value) {
    return $value ? 'this value is true' : 'this value is false';
}

This works by checking if the first section evaluates to true, if it does that the second section will return, if it's not true then we return the third section.

Checking If Variable Isset

The second area we need to look at to help improve our code is the use of the isset or !empty. You may see this is code as it's quite a common situation where we need to check if a variable isset or not null you may see something like this.


function issetCheck($input) {
    if(!isset($input['text'])) {
        return 'Default';
    }

    return $input['text'];
}

In PHP 7 a new operator was introduced called the Null coalescing operator which consists of two ?? it's very useful when checking for values in arrays or assigning defaults if a variable is not set. Instead of the above you can use something like this.


function issetCheck($input) {
    return $input['text'] ?? 'Default';
}

This works by going is the $input['code'] set in the array if it is then return this value, if it's not set then use the right side of the operator which in this case is Default. This can also work for variables where you need to check if something is null before you do something with it. This is common on parameters of a function where you want to give it a default value if it's null, giving defaults to the parameters you pass into a function.

Login to access all content on Paulund

Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email