Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Null coalescing operator and spaceship operator

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 114
    Comment on it

    Welcome to Findnerd. Today we are going to discuss the Null coalescing operator and spaceship operator which are added in PHP7. Null coalescing operator is enchanced version of ternary operator. You should be familar with the ternary operator. We use the ternary opertor like this.

    $data = if(isset($_GET['data']) ? $_GET['data'] : 'blank';
    

    You can use the same code with Null coalescing operation like this

    $data = $_GET['data'] ?? 'nodata';
    

    You can also build the chain for the same like this

    $data = $_GET['data'] ?? $_GET['default'] ?? 'nodata';
    

    In above sample, it will try for data and if data parameter is not available then it will try for default. If it fails in both then it will pass the value nodata to variable. It is useful to avoid the lengthy conditions.

    In other hand we have spaceship operators which are useful to compare two expressions. It will return the values -1,0,1 when first expension is less,equal or greater than the second. Please have a look

    echo 1<=>2; 
    result: -1
    
    echo 1<=>1;
    result: 0;
    
    echo 2<=>1;
    echo 1;
    
    other example for alphabets
    
    echo "a"<=>"b";
    result: -1
    echo "a"<=>"a";
    result: 0
    echo "b"<=>"a";
    result: 1
    

 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: