📅  最后修改于: 2023-12-03 15:33:39.882000             🧑  作者: Mango
In PHP, there are two shorthand operators that can be used to simplify if-else statements: ?:
and ??
.
?:
OperatorThe ?:
operator is a ternary operator, which means it takes three operands. It is used to provide a shortcut for the if-else statement.
<?php
$name = "John";
// Using if-else statement
if($name == "John"){
echo "Hello, John!";
}else{
echo "Hello, Stranger!";
}
// Using ?: operator
$message = ($name == "John" ? "Hello, John!" : "Hello, Stranger!");
echo $message;
?>
Output:
Hello, John!
Hello, John!
??
OperatorThe ??
operator is called the null coalescing operator. It is used to check if a variable is null and provide a default value if it is.
<?php
// Using if-else statement
if(isset($_GET['name'])){
$name = $_GET['name'];
}else{
$name = "Stranger";
}
// Using ?? operator
$name = $_GET['name'] ?? "Stranger";
?>
<form action="" method="get">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<button type="submit">Submit</button>
</form>
<p>Hello, <?php echo $name; ?>!</p>
Output:
Hello, Stranger!
In summary, the ?:
operator is used to simplify if-else statements, while the ??
operator is used to check if a variable is null and provide a default value. These shorthand operators can help to write cleaner and more readable code.