Something I'm not exactly clear on, how does ??
, ?:
, and ??=
differ in PHP?
I know ??=
was only added in PHP7.4.
I also know that ??
is for checking null values, but ?:
also seems to check for null values, so I'm not entirely sure of the difference.
My Answer:
The three operators ??, ?:, and ??= serve different purposes in PHP:
1. ?? (Null Coalescing Operator): This operator is used to check if a variable is set and not null. If the variable is set and not null, it returns its value; otherwise, it returns a default value. For example:
php
$name = $firstName ?? 'Guest';
In this example, if $firstName is set and not null, $name will be assigned the value of $firstName. If $firstName is null or not set, $name will be assigned the value 'Guest'.
2. ?: (Ternary Operator): This operator is a shorthand way of writing an if-else statement. It checks a condition and returns one value if the condition is true, and another value if the condition is false. For example:
php
$age = 20;
$message = ($age >= 18) ? 'Adult' : 'Minor';
In this example, if $age is greater than or equal to 18, $message will be assigned the value 'Adult'. Otherwise, $message will be assigned the value 'Minor'.
3. ??= (Null Coalescing Assignment Operator): This operator was introduced in PHP 7.4 and combines the null coalescing operator (??) with the assignment operator (=). It assigns a value to a variable only if the variable is not set or is null. For example:
php
$color ??= 'blue';
In this example, if $color is not set or is null, it will be assigned the value 'blue'. If $color is already set to a non-null value, it will not be changed.
In summary, ?? is used to provide a default value for a variable if it is null, ?: is used for conditional assignment based on a condition, and ??= is used to assign a value to a variable only if it is not set or is null.
Rate this post
5 of 5 based on 1427 votesComments