📜  php?? vs ?: - PHP (1)

📅  最后修改于: 2023-12-03 15:33:39.882000             🧑  作者: Mango

PHP ?: vs ?? Operators

In PHP, there are two shorthand operators that can be used to simplify if-else statements: ?: and ??.

The ?: Operator

The ?: operator is a ternary operator, which means it takes three operands. It is used to provide a shortcut for the if-else statement.

Example
<?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!
The ?? Operator

The ?? 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.

Example
<?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!
Conclusion

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.