Shorthand Comparisons in PHP

Shorthand Comparisons in PHP
Shorthand Comparisons in PHP

In Programming, shorthand is writing same piece of code in shorter way. Shorthand comparisons in PHP comprise of minimal use of code for better reading & usability.

In this tutorial, we’ll learn which shorthand syntax PHP has added and will understand usability of it with practical approach.

Shorthand comparisons in PHP consists of –

  • Shorthand Ternary Operator
  • Null Coalescing Operator
  • Spaceship Operator

First, we’ll understand the most basic and most important condition which we regularly use in day to day coding. The if statement.

PHP if shorthand

Like many other languages, the if construct is one of the most important features of the PHP as well. if statement evaluates the condition inside it as either TRUE or FALSE. If TRUE then code inside the curly brackets gets executed otherwise not.

Basic Syntax –

if($condition) {

  // execute inside it once condition becomes true only.

}

Let’s write some code and then we will understand it, based on the logic written inside it.

<?php

class event
{

    public $event_start_dt;
    public $event_end_dt;

    public function __construct($event_start_date, $event_end_date)
    {
        $this->event_start_dt = $event_start_date;
        $this->event_end_dt   = $event_end_date;
    }

    public function check_event_date($current_date)
    {
        if ($current_date > $this->event_start_dt && 
            $current_date < $this->event_end_dt) {

            return TRUE;
        } else {
            return FALSE;
        }
    }
}

$obj_event = new event("2020-05-01", "2020-05-31");
$date_check = $obj_event->check_event_date(date("Y-m-d"));

?>

In the above example, we have defined a class and assigned $event_start_date & $event_end_date to the class level variables and then inside check_event_date() function we are using if condition to check whether current date is in between these two dates OR not. If that meets the condition then it will return TRUE otherwise FALSE.

Now, we’ll modify the check_event_date() function and will optimize if condition by removing the else block but keeping return statement. This is because we want to return either of the boolean value and it doesn’t make sense to keep it as there is no other use of the variables.

<?php

public function check_event_date($current_date) {
        if($current_date > $this->event_start_dt && 
           $current_date < $this->event_end_dt) {

            return TRUE;
        }
        
        return FALSE;
}

?>

Now, code looks very clean but can we make it more cleaner. Yes, we can use something called as Ternary Operator OR in short php if else shorthand.

Ternary Operator

Basic Syntax –

$result = $condition ? Expr1 : Expr2;

As we can see, if $condition is evaluated to TRUE then only it will return the value present right after “?” else it will return value present after “:

This way, code looks much cleaner and readable. Now, we will apply the same changes in our check_event_date() function.

<?php

public function check_event_date($current_date) {
        return ($current_date > $this->event_start_dt && 
                $current_date < $this->event_end_dt) ? TRUE : FALSE;
}

?>

With the ternary operator, if the First condition evaluates to TRUE then it will return TRUE and if the first expression evaluates to FALSE then it will return FALSE.

Like in our example, we can use as many condition in the first expression as we like (which can add in the if condition) and this will return boolean only. Check PHP type comparison table to know more about the different conditions and value based on the that condition.

PHP Shorthand Ternary Operator

Now, Since PHP 5.3, it is also possible to ignore the middle part of the ternary operator and hence code will look this condition?:Expr.

If the condition evaluates to TRUE then it will return boolean value generated by the condition statement otherwise will return the other value.

<?php

public function check_event_date($current_date) {
        return ($current_date > $this->event_start_dt && 
                $current_date < $this->event_end_dt) ?: FALSE;
}

?>

Null Coalescing Operator / php 7 ?? operator

In extend to Ternary Operator, the null coalescing operator “??” is available as of PHP 7.0.0

Basic Syntax-

(expression1) ?? (expression2)

As compared to Ternary Operator, in Null Coalescing Operator, the expression1 ?? expression2 evaluates to expression1 if expression1 is not NULL, otherwise expression2.

Basically Null Coalescing Operator works same like isset() function which evaluates all values to true except following

  • $y = null;
  • var $y;
  • $y is undefined

For more details refer this comparison of variable with PHP functions table.

<?php

// Null Coalesce Operator Example
$result = $action ?? 'default';

// The above is very identical to this if else statement
if (isset($action )) {
    $result = $action;
} else {
    $result = 'default';
}

?>

In the above example, if the $action is not defined then it will not generate any PHP Notice Error but rather it will return false and hence output of the first statement is default

In the later statement, it is a regular method of evaluating our variable where we check $action variable with isset() function and if that value is set then whatever the value stored in the $action is stored in the $result variable otherwise 'default' is stored in the $result

Let’s understand null Coalesce Operator using Array() because with it we can go deeper inside the array and evaluate each value easily.

<?php

$employee_details = [
    'name' => 'John',
    'age'  => 30,
    'employment' => [
        'office_location' => 'New York',
        'designation' => 'Type Writer'
        ]
    ];

echo $employee_details ['name'] ?? 'default';
echo $employee_details ['employment']['office_location'] ?? 'default';
echo $employee_details ['desk_location'] ?? 'default';

?>
// OUTPUT

John
New York
default

spaceship operator php

Introduced in PHP 7.0.0. This feature enables us to compare two expressions. It returns -1, 0 OR 1 when value at left hand side is less than, equal to OR greater than right hand side value.

With the spaceship operator, shorthand comparisons in PHP, reaches to new level and it gives developers a quick solution to what we need to do before by writing long code for small result.

Two values can either be integer, float, string, array and objects.

<?php

// Integer
echo 0 <=> 1;
echo 1 <=> 1;
echo 1 <=> 0;

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// String
echo 'a' <=> 'b';
echo 'b' <=> 'b';
echo 'c' <=> 'b';

// Array
echo [0, 1] <=> [0, 1, 2];
echo [0, 1] <=> [0, 1];
echo [0, 1, 2] <=> [0, 1];

// Object

echo (object) [0, 1] <=> (object) [0, 1, 2];
echo (object) [0, 1] <=> (object) [0, 1];
echo (object) [0, 1, 2] <=> (object) [0, 1];

?>
// OUTPUT

-1
0
1

-1
0
1

-1
0
1

-1
0
1

-1
0
1

Conclusion:

PHP has evolved so much in its lifetime. It’s keep evolving day by day. With PHP 7 release it has touched new heights. All the above mentioned shorthand comparisons in php, we have seen some cool features in the PHP. You can use them whenever it is required.