Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • New Feature in Php 7

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 101
    Comment on it

    One of the New Feature of PHP 7 is Null coalescing operator :


     Generally we use to check variable value existence and if it does not exist then we use a default value for that.  Normally for these type of small checks we use Ternary operators.      

      $param = isset($_POST['param']) ? $_POST['param'] : 'default';

     

    Php 7 introduces a new operator " Null Coalesce Operator" .
    This operator return first value if it exist and  not null else return second value.  

          $param = $_POST['param'] ?? 'default';

           
     Both of the above statements of  Ternary and Coalesce Operator are equivalent.
     The advantage is new operator is having short and concise code

    The new operator can also be used in following ways:

     

    In Example 1 as you can see we have Typo 2 times. So it will check for those variables and as they does not exist so it will finally print the value of last parameter .

    Line 3 it will raise warning for second as both of the values are not defined.

    Example 1:

            $arr = ["param" => "How are you ?"];
            var_dump($arr["parm"] ?? $arr["paam"] ?? $arr["param"]); // string(16) "How are you ?"
            var_dump($arr["parm"] ?? $arr["paam"]); //<b>Notice</b>:  Undefined index: paam in <b>

     

    Example 2:

            $iParam1 = NULL;
            $iParam2 = NULL;
            $iParam3 = 3;
            var_dump($iParam1 ?? $iParam2 ?? $iParam3); // int(3)

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: