PHP Related
Check if Variable is Null (isset())
You can use isset() to determine if a variable is declared and is different than null. It returns false when checking variables that has been assigned to null, this exclude the false boolean value; i.e. isset(false) will return true.
You can perform ternary operation using isset() to set value if it is null:
| |
(*There’s also empty() and is_null() but they have some slightly difference , you can refer to the following table I copied from this stack-overflow post for reference:
| “foo” | "" | 0 | “0” | FALSE | NULL | [] | (object) [] | undefined | |
|---|---|---|---|---|---|---|---|---|---|
empty() | FALSE | TRUE | TRUE | TRUE | TRUE | TRUE | TRUE | FALSE | TRUE |
is_null() | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE (ERROR) |
isset() | TRUE | TRUE | TRUE | TRUE | TRUE | FALSE | TRUE | TRUE | FALSE |
Null Coalescing Operator/Assignment (??/??=)
(For PHP <7.4) You can use ?? to assign value to a new variable, or set fallback value if the source if null:
| |
(For PHP ≥7.4) You can use ??= to assign value to variable when it is null:
| |
Null-Safe Operator (?->)
If you need to access a property or method on an object that might be null, use the null-safe operator. This prevents “Call to a member function on null” errors.
| |
Twig Related
Check if Variable is Null ({{var is null}})
You can use is null to check if a variable is null (note that none is just another alias for null), and you can use ternary operation (?:) to assign a default values when certain variable is null.
| |
(*Please note that: when an object is null, it cannot be undefined, so to capture all the cases, we’ll usually use the following:
| |
Null Coalescing Operator (??)
You can use ?? to assign default value when a variable is null (identical to php):
| |
Null-Safe Operator (?.)
The null-safe operator (?.) enables safe navigation through values that may be null. If the left operand is null, it returns null instead of throwing an exception.
| |