Conditional Assignment Operator in PHP is a shorthand operator that allow developers to assign values to variables based on certain conditions.

In this article, we will explore how the various Conditional Assignment Operators in PHP simplify code and make it more readable.

PHP Conditional Operator: The Ternary Operator (? : )

The Conditional Operator, also known as the Ternary Operator, assigns values to variables based on a certain condition. It takes three operands: the condition, the value to be assigned if the condition is true, and the value to be assigned if the condition is false.

Here’s an example:

<?php 
$score = 85;
$result = ($score >= 60) ? "Pass" : "Fail";
echo $result; // Outputs "Pass"

In this example, the condition is $score >= 60. If this condition is true, the value of $result is “Pass”. Otherwise, the value of $result is “Fail”.

To learn more about it, visit PHP ternary operator tutorial.

The Null Coalescing Operator (??)

The Null Coalescing Operator, also known as the Null Coalescing Assignment Operator, assigns a default value to a variable if it is null. The operator has two operands: the variable and the default value it assigns if the variable is null. Here’s an example:

<?php 
$name = $_GET['name'] ?? "Guest";
echo "Welcome, $name!";

So, In this example, if the $_GET['name'] variable is null, the value of $name is “Guest”. Otherwise, the value of $name is the value of $_GET['name'].

The Null Coalescing Assignment Operator (??=)

The Null Coalescing Operator with Assignment, also known as the Null Coalescing Assignment Operator, assigns a default value to a variable if it is null. The operator has two operands: the variable and the default value it assigns if the variable is null. Here’s an example:

<?php 
$name = null;
$name ??= "Guest";
echo "Welcome, $name!";

So, the value of $name is null. The Null Coalescing Assignment Operator assigns the value “Guest” to $name. Therefore, the output of the echo statement is “Welcome, Guest!”.

The Elvis Operator (?:)

In another hand, The Elvis Operator is a shorthand version of the Ternary Operator. Which assigns a default value to a variable if it is null. It takes two operands: the variable and the default value to be assigned if the variable is null. Here’s an example:

<?php 
$name = $_GET['name'] ?: "Guest";
echo "Welcome, $name!";

In this example, if the $_GET['name'] variable is null, the value of $name is “Guest”. Otherwise, the value of $name is the value of $_GET['name'].

Wrapping Up

In conclusion, the Conditional Assignment Operators in PHP provide developers with powerful tools to simplify code and make it more readable. You can use these operators to assign values to variables based on certain conditions, assign default values to variables if they are null, and perform shorthand versions of conditional statements. By using these operators, developers can write more efficient and elegant code.

To learn more, visit PHP manual.