How Is null Comparison Done When Using the PHP Spaceship Operator (<=>)?

Comparing null with different values using the PHP spaceship operator (<=>) follows the same rules as with other comparison operators (as outlined in the official PHP docs) — i.e., the following rules apply:

  1. null is always smaller than truthy values:

    echo null <=> true; // -1
    echo null <=> 1; // -1
    echo null <=> 1.0; // -1
    echo null <=> [1, 2, 3]; // -1
    // ...
    
  2. null is converted to an empty string ("") for numerical or lexical comparison, and is, therefore, always smaller than other (non-empty) strings:

    echo null <=> '0'; // -1
    echo null <=> 'abc'; // -1
    
  3. null is equal to all falsy values (except '0'):

    echo null <=> null; // 0
    echo null <=> false; // 0
    echo null <=> ''; // 0
    echo null <=> 0; // 0
    echo null <=> 0.0; // 0
    echo null <=> []; // 0
    echo null <=> (bool) new SimpleXMLElement('<foo />'); // 0
    

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.