Home > Article > Backend Development > In php, what is the difference between ternary operator and null coalescing operator?
The ternary operator is used to replace an if else statement with a single statement.
(condition) ? expression1 : expression2;
if(condition) { return expression1; } else { return expression2; }
If the condition is true, return the result of expression 1, otherwise return the result of expression 2. void is not allowed in conditions or expressions.
The null coalescing operator is used to provide a non-null value when the variable is empty.
(variable) ?? expression;
if(isset(variable)) { return variable; } else { return expression; }
If the variable is empty, the result of the expression is returned.
<!DOCTYPE html> <html> <head> <title>PHP Example</title> </head> <body> <?php // fetch the value of $_GET['user'] and returns 'not passed' // if username is not passed $username = $_GET['username'] ?? 'not passed'; print($username); print("<br/>"); // Equivalent code using ternary operator $username = isset($_GET['username']) ? $_GET['username'] : 'not passed'; print($username); print("<br/>"); ?> </body> </html>
not passed not passed
The above is the detailed content of In php, what is the difference between ternary operator and null coalescing operator?. For more information, please follow other related articles on the PHP Chinese website!