Tutorial

PHP 7 – New Operators

PHP people are hoping for release of PHP 7 in 2015. So 2015 is being considered as an important year for PHP as it’s been 11 years for release of PHP 5. As this is about be very be very major release of PHP, it has lot many things added, lot many things removed which was deprecated since long and many other things marked as deprecated as well.

I have started this article series to cover things which are new, deprecated and eliminated from PHP 7. In this article, we will be looking into new operators available in PHP 7.

PHP 7 - New Operator

PHP 7 ships with two new cool operators which are as below:

  1. Spaceship Operator
  2. Null Coalesce Operator

Spaceship Operator

This is going to be very useful as its a shorthand for various if else conditions in your code. This operator is noted as [code]<=>[/code] and also known as combined comparison operator.

If you want to compare $a with $b then you can use like [code]$a <=> $b[/code]. This expression will return -1 if $a < $b, 0 if $a = $b, and 1 if $b > $a. In other words we can consider this new operator as a shortcut for below like of code.

[cc lang=”php”]
// below lines performs the same thing in PHP7

// Old way
($a < $b) ? -1 : (($a > $b) ? 1 : 0)

// New way
$a <=> $b
[/cc]

null coalesce operator

Same as “Spaceship Operator“, this operator is also a shorthand for commonly used condition, and symbol for this operator is [code]??[/code]. Null Coalesce Operator can be used with one variable and it will check if any value set for that variable then it will return already set value else it will return default value which is defined. Let’s look into some code now:

[cc lang=”php”]
// below lines performs the same thing in PHP7

// Old Way
$a = isset($b) ? $b : ‘0’;

// New way
$a = $b ?? ‘0’
[/cc]

Cool, Isn’t it? Yes I am feeling the same because this will reduce few characters in your code and more readable. In upcoming article we will see what are the new changes for Type Hinting we will receive in PHP7.

Shares:
  • Omid
    Omid
    July 26, 2015 at 11:43 pm

    spaceship is same as , is’nt? :) :
    ‘;

    $a = 12;
    $b = 1;

    echo strcmp($a , $b);
    //1
    echo ‘
    ‘;

    $a = 12;
    $b = 1;

    echo strcmp($b , $a);
    //-1
    echo ‘
    ‘;

    Reply
    • Avinash
      July 27, 2015 at 12:56 pm

      Yes it is similar to strcmp but not fully similar. This operator is combination of various operator. Look at definition on php.net

      This RFC adds a new operator for combined comparison. Similar to strcmp() or version_compare() in behavior, but it can be used on all generic PHP values with the same semantics as <, <=, ==, >=, >.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *