Operators in PHP are signs and symbols which are used to indicate that a particular operation should be performed on an operand in an expression. Operands are the operation objects, or targets. An expression contains operands and operators arranged in a logical manner.
In PHP, there are numerous operators, which are grouped into the following categories:
Conditional assignment operators
Some examples of these operators are:
--and so much more.
Conditional assignment operators, as the name implies, assign values to operands based on the outcome of a certain condition. If the condition is
true, the value is assigned. If the condition is
false, the value is not assigned.
There are two types of conditional assignment operators: tenary operators and null coalescing operators.
$y = expr1 ? expr2 : expr3;
expr3 are either expressions or variables.
From the syntax, the value of
$y will be evaluated.
This value of
$y is evaluated to
The value of $y is
?? operator was introduced in PHP 7 and is basically used to check for a NULL condition before assignment of values.
$z = varexp1 ?? varexp2;
varexp2 are either expressions or variables.
The value of
varexp1 if and only if
varexp1 exists, and is not NULL.
varexp1 does not exist or is NULL, the value of
Let’s use some code snippets to paint a more vivid description of these operators.
<?php /*** Ternary operator ***/ $expr1 = 7 > 10; $expr2 = "New y value if expr1 is true"; $expr3 = "New y value if expr1 is false"; //$y takes the value of $expr3 because $expr1 is false $y = $expr1 ? $expr2:$expr3; echo $y; /**** Null coalescing operator ****/ echo "\n"; //set varexp1 value to null $varexp1 = null; // set varexp2 value to string. $varexp2 = "new z value as varexp1 is null"; $z = $varexp1 ?? $varexp2; echo $z; ?>
In the code above, the new value of
$z is set based on the evaluation result of
View all Courses