PHP Conditional Assignment Operators

Rumman Ansari   Software Engineer   2020-02-06   5814 Share
☰ Table of Contents

Table of Content:


The PHP conditional assignment operators are used to set a value depending on conditions:

Operator Name Example Result
?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.
The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE
?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.
The value of $x is expr1 if expr1 exists, and is not NULL.
If expr1 does not exist, or is NULL, the value of $x is expr2.
Introduced in PHP 7

Example: ?: Ternary

Code:


<!DOCTYPE html>
<html>
<body>

<?php
   // if empty($user) = TRUE, set $status = "unknown"
   echo $status = (empty($user)) ? "unknown" : "logged in";
   echo("<br>");

   $user = "Rambo Azmi";
   // if empty($user) = FALSE, set $status = "logged in"
   echo $status = (empty($user)) ? "unknown" : "logged in";
?>  

</body>
</html>


Output:

The above code will produce the following result-


unknown
logged in

Example:

Code:


<!DOCTYPE html>
<html>
<body>

<?php
   // if empty($user) = TRUE, set $status = "unknown"
   echo $status = (empty($user)) ? "unknown" : "logged in";
   echo("<br>");

   $user = "Rambo Azmi";
   // if empty($user) = FALSE, set $status = "logged in"
   echo $status = (empty($user)) ? "unknown" : "logged in";
?>  

</body>
</html>


Output:

The above code will produce the following result-


unknown
logged in