Null Coalescing in PHP Snippet and Tutorial

In this tutorial, you will learn how to use Null Coalescing using PHP Language. The tutorial aims to provide IT/CS students and new programmers with a reference for learning the different techniques and usage of the PHP built-in methods and operators. Here, snippets are provided for better understanding, and a sample source code zip file is also provided and is free to download.

What is a Null Coalescing operator?

Null Coalescing is also known as the Logical Defined-Or Operator in Perl. It is a binary operator of the syntax for basic conditional expressions in most programming languages. Using this operator, you can evaluate if the given variables or constants are set or not null and return the first not null and set instance.

How to implement Null Coalescing in PHP?

In PHP, the old way of doing this is using the conditional shorthand if statement which requires you to check first if the given variable or constant is existing/set and not null. In PHP version 7 up to the latest, PHP comes with the ?? or the Null Coalescing Operator. This operator automatically evaluates the variables and constants. It will return the first instance that is set and not null.

The syntax of usage of the Null Coalescing Operator is like the following snippet:

  1. <?php
  2. //Old way
  3. $x = isset($a) ? $a : $b;
  4.  
  5. //New way
  6. $x = $a ?? $b;
  7. ?>

As you can see in the sample snippet above, the new way of Null Coalescing in PHP is more likely easier and less coding while both ways will return the same value;

Example

Null Coalescing in PHP

Here is the script of a simple web application that demonstrates both the old and new way of writing a null coalescing syntax using the PHP's built-in isset() method and null coalesce operator.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>PHP - Null Coalescing</title>
  7.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9.     <link rel="stylesheet" href="assets/css/styles.css">
  10.     <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  11.     <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
  12.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  13.  
  14.     <script src="assets/js/script.js"></script>
  15.     <style>
  16.        
  17.     </style>
  18. </head>
  19.     <main>
  20.         <nav class="navbar navbar-expand-lg navbar-dark bg-gradient">
  21.             <div class="container">
  22.                 <a class="navbar-brand" href="./">PHP - Null Coalescing</a>
  23.                
  24.                 <div>
  25.                     <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  26.                 </div>
  27.             </div>
  28.         </nav>
  29.         <div id="main-wrapper">
  30.             <div class="container px-5 my-3" >
  31.                 <script>
  32.                     start_loader()
  33.                 </script>
  34.                 <div class="mx-auto col-lg-8 col-md-10 col-sm-12 col-xs-12">
  35.                     <div class="card rounded-0 mb-3 shadow">
  36.                         <div class="card-header rounded-0">
  37.                             <div class="card-title"><b>Null Coalescing</b></div>
  38.                         </div>
  39.                         <div class="card-body rounded-0">
  40.                             <div class="container-fluid">
  41.                                 <div class="bg-dark text-light" style="height: 35vh; overflow: auto;">
  42.                                     &lt;?php
  43.                                     <br>
  44.                                     <span class="text-muted">//Coalescing using PHP isset() method</span><br>
  45.                                     <span class="text-info">$page</span>  = <span class="text-warning">isset</span>(<span class="text-info">$_GET</span><span class="text-primary">[</span><span class="text-warning">'page'</span><span class="text-primary">]</span>) ? <span class="text-info">$_GET</span><span class="text-primary">[</span><span class="text-warning">'page'</span><span class="text-primary">]</span> : "home";<br>
  46.                                     <span class="text-info">echo</span> "&lt;label class='text-muted fw-light fst-italic'&gt;Page Variable using <span class="text-warning">isset</span>() method:&lt;/label&gt;";<br>
  47.                                     <span class="text-info">echo</span> "&lt;div class='ps-4 fw-bolder'&gt;{<span class="text-info">$page</span>}&lt;/div&gt;";<br>
  48.                                     <br>
  49.                                     <br>
  50.                                     <span class="text-muted">//Coalescing using PHP ?? operator</span><br>
  51.                                     <span class="text-info">$page</span> = <span class="text-info">$_GET</span><span class="text-primary">[</span><span class="text-warning">'page'</span><span class="text-primary">]</span> ?? "home";<br>
  52.                                     <span class="text-info">echo</span> "&lt;label class='text-muted fw-light fst-italic'&gt;Page Variable using ?? Operator&lt;/label&gt;";<br>
  53.                                     <span class="text-info">echo</span> "&lt;div class='ps-4 fw-bolder'&gt;{<span class="text-info">$page</span>}&lt;/div&gt;";<br>
  54.                                     <br>
  55.                                     <br>
  56.                                     <span class="text-muted">//Multiple in-line Coalescing using PHP isset method;</span><br>
  57.                                     <span class="text-info">$postID</span> = <span class="text-warning">isset</span>(<span class="text-info">$_GET</span><span class="text-primary">[</span><span class="text-warning">'id'</span><span class="text-primary">]</span>) ? <span class="text-info">$_GET</span><span class="text-primary">[</span><span class="text-warning">'id'</span><span class="text-primary">]</span> : (<span class="text-warning">isset</span>(<span class="text-info">$_GET</span><span class="text-primary">[</span><span class="text-warning">'postID'</span><span class="text-primary">]</span>) ? <span class="text-info">$_GET</span><span class="text-primary">[</span><span class="text-warning">'postID'</span><span class="text-primary">]</span> : "Variable is NULL");<br>
  58.                                     <span class="text-info">echo</span> "&lt;label class='text-muted fw-light fst-italic'&gt;PostID Variable using <span class="text-warning">isset</span>() method:&lt;/label&gt;";<br>
  59.                                     <span class="text-info">echo</span> "&lt;div class='ps-4 fw-bolder'&gt;{<span class="text-info">$postID</span>}&lt;/div&gt;";<br>
  60.                                     <br>
  61.                                     <br>
  62.                                     <span class="text-muted">//Multiple in-line Coalescing using PHP ?? Operator;</span><br>
  63.                                     <span class="text-info">$postID</span> = <span class="text-info">$_GET</span><span class="text-primary">[</span><span class="text-warning">'id'</span><span class="text-primary">]</span> ?? <span class="text-info">$_GET</span><span class="text-primary">[</span><span class="text-warning">'postID'</span><span class="text-primary">]</span> ?? "Variable is NULL";<br>
  64.                                     <span class="text-info">echo</span> "&lt;label class='text-muted fw-light fst-italic'&gt;PostID Variable using ?? operator:&lt;/label&gt;";<br>
  65.                                     <span class="text-info">echo</span> "&lt;div class='ps-4 fw-bolder'&gt;{<span class="text-info">$postID</span>}&lt;/div&gt;";
  66.                                     <br>
  67.                                     ?&gt;
  68.                                     <br>
  69.                                 </div>
  70.                                 <?php
  71.                                //Coalescing using PHP isset() method
  72.                                $page  = isset($_GET['page']) ? $_GET['page'] : "home";
  73.                                echo "<label class='text-muted fw-light fst-italic'>Page Variable using isset() method:</label>";
  74.                                 echo "<div class='ps-4 fw-bolder'>{$page}</div>";
  75.  
  76.                                 //Coalescing using PHP ?? operator
  77.                                 $page = $_GET['page'] ?? "home";
  78.                                 echo "<label class='text-muted fw-light fst-italic'>Page Variable using ?? Operator</label>";
  79.                                 echo "<div class='ps-4 fw-bolder'>{$page}</div>";
  80.  
  81.                                 //Multiple in-line Coalescing using PHP isset method;
  82.                                 $postID = isset($_GET['id']) ? $_GET['id'] : (isset($_GET['postID']) ? $_GET['postID'] : "Variable is NULL");
  83.                                 echo "<label class='text-muted fw-light fst-italic'>PostID Variable using isset() method:</label>";
  84.                                 echo "<div class='ps-4 fw-bolder'>{$postID}</div>";
  85.                                
  86.                                 //Multiple in-line Coalescing using PHP ?? Operator;
  87.                                 $postID = $_GET['id'] ?? $_GET['postID'] ?? "Variable is NULL";
  88.                                 echo "<label class='text-muted fw-light fst-italic'>PostID Variable using ?? operator:</label>";
  89.                                 echo "<div class='ps-4 fw-bolder'>{$postID}</div>";
  90.                                 ?>
  91.                             </div>
  92.                         </div>
  93.                     </div>
  94.                 </div>
  95.             </div>
  96.         </div>
  97.         <footer class="bg-gradient bg-light shadow-top py-4 col-auto">
  98.             <div class="">
  99.                 <div class="text-center">
  100.                     All Rights Reserved &copy; <span id="dt-year"></span> | <span class="text-muted">PHP - Null Coalescing</span>
  101.                 </div>
  102.                 <div class="text-center">
  103.                     <a href="mailto:[email protected]" class="text-decoration-none text-success">[email protected]</a>
  104.                 </div>
  105.             </div>
  106.         </footer>
  107.     </main>
  108.    
  109. </body>
  110. </html>

DEMO VIDEO

Save the script above as a PHP File and try to run it on your end to test it if works properly and meets the main objectives of this tutorial.

I also have provided a simple web application source code zip file that I created for this tutorial on this website. It is free to download and can be downloaded by clicking the Download Button located below this article's content.

That's the end of this tutorial! I hope this Null Coalescing in PHP Tutorial will help you with what you are looking for and will be useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =>

Add new comment