PHP MYSQL - Operators - 5.8 Conditional Assignment Operators

 

PHP Conditional Assignment Operators

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

OperatorNameExampleResult
?:Ternary$x = expr1 ? expr2 : expr3Returns 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 ?? expr2Returns 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
<!DOCTYPE html>
<html>
<body>

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

   $user = "John Doe";
   // if empty($user) = FALSE, set $status = "logged in"
   echo $status = (empty($user)) ? "anonymous" : "logged in";
?>  

</body>
</html>

Output:

anonymous
logged in

<!DOCTYPE html>
<html>
<body>

<?php
   // variable $user is the value of $_GET['user']
   // and 'anonymous' if it does not exist
   echo $user = $_GET["user"] ?? "anonymous";
   echo("<br>");
  
   // variable $color is "red" if $color does not exist or is null
   echo $color = $color ?? "red";
?>  

</body>
</html>

Output:
anonymous
red

Popular posts from this blog

COPA Bits for Computer Based Test (CBT) by Venugopal Vanjarapu

COPA

Web Designing course - HTML, CSS live classes