PHP

PHP Magic - the Null Coalescing Operator (??) - return the value if the give variable is NULL

CK CK 3788 
Created at  
1,681 0 0

The PHP Null Coalescing Operator (??) is a convenient way to handle situations where a variable or an array element might be null or undefined. It provides a concise syntax for choosing a default value when the variable or array element is null or does not exist.

Syntax:

$variable = $value ?? $default;

 

Explanation:

If $value is not null, $variable will be assigned the value of $value.

If $value is null, $variable will be assigned the value of $default.

Example Usage:

1. Using with Variables:

$username = $input_username ?? 'Guest';

 

In this example, if $input_username is set and not null, $username will be assigned its value. Otherwise, $username will be assigned the default value 'Guest'.

2. Using with Array Elements:

$value = $array['key'] ?? $default;

 

Here, if the key 'key' exists in $array and its value is not null, $value will be assigned that value. If the key doesn't exist or its value is null, $value will be assigned the default value $default.

Notes:

The null coalescing operator was introduced in PHP 7.0, so make sure you are using PHP 7.0 or later versions.

It's especially useful for avoiding "undefined variable" or "undefined index" notices in your code.

The null coalescing operator is a handy tool for writing clean and concise PHP code, especially when dealing with potentially null values.

Tags PHP Magic PHP Null Coalescing Operator PHP Shortcut Facebook X
Comments 0
  1. Upgrading PHP 7.4 to PHP 8.1 in CentOS 7
    653
  2. gRPC Server with PHP
    509
  3. PHP Code to Fetch current Coinbase Assets (Balances)
    444
  4. PHP Code to Fetch PEPE coin pricing based in USD from Coinbase
    366
  5. Google Single Sign-On implementation with PHP
    1,381
  6. PHP Superglobal Variables do not require additional syntax to access it
    2,656
  7. Run Python Code with Virtual Environment in PHP
    675
  8. PHP Simplified Operators
    318
  9. PHP Heredoc (aka Nowdoc)
    447
  10. PHP Post Processing by disconnecting HTTP connection and continuing the remaining logics
    1,824
  11. WordPress Remote Posting with PHP
    1,700
  12. Google BigQuery Example to converted Nested FIelds in JSON
    461
  13. Verifying Apple In-App Purchase validation receipt with PHP
    1,803
  14. Useful code for file-based Unit Test in PHP
    507
  15. Function Overloading Implementation in PHP with Magic Mathods
    1,764
  16. How do I find php.ini on Mac?
    495
  17. Mastering Excel Data Importation in PHP
    558
  18. Create Blob Image in HTML based on the given Text, Width and Height in the Center of the Image without saving file
    986
  19. How do I determine the client IP type (IPv4/IPv6) in PHP
    840
  20. What is 302 Found Redirection in HTTP 1.1?
    497
  21. Implementing a Versatile DNS Server in PHP: Handling A, AAAA, CNAME, and TXT Records
    624
  22. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    746
  23. CentOS 7 PHP Apache Kafka: Installation, Examples, and System Diagram
    311
  24. Apache Kafka Explained: Powering Netflix, Building with PHP
    495
  25. Array of arguments passed to script in PHP
    97
  26. Bob Jenkins' One-At-A-Time hashing algorithm in PHP
    57
  27. 32bits simple hash function in PHP
    44
  28. PHP Code Compression Tool by removing whitespace, strips comments - PHP Minifier/Compressor
    1,426
  29. Setup Apache+PHP+MySQL on Centos 6.7
    609
  30. mcrypt missing when using phpMyAdmin on Centos 6.7
    555
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,910
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Invalid Auction Storms in Ad Tech
    106
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  10. The Two Clocks of Ad Server Architecture
    77
  11. Frequency Cap Architecture Overview
    526
  12. Collecting Proof-of-Play from 100,000 Screens
    152
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  14. What is RedisVL?
    114
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  16. TPU & GPU Cluster Management Tools
    257
  17. The Concept of Scaffolding in AI Agents
    244
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  22. Machine Learning: Training vs. Ranking
    229
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  25. Designing a Data Curation System Around a Vector Database
    230
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    672
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232
  30. Understanding Data Lineage
    271