PHP Conditional assignment operators
Register here to save your progress
The use of this type of operators is to assign the value of a variable depending on a condition.
The conditional assignment operators are:
- the thernary operator
- the null coalescing operator (introduced in PHP version 7)
What decides which value will the variable get, when using a conditional assignment operators?
The thernary operator will assign the value of a variable after evaluating a statement. If the statement it's true, it will try return its left side to the variable, else it will return the right side.
|Thernary||? :||$a = statement1 ? stament2 : statement3||
Will assign the value of statement2 if stament1 is true
Will assign the value of statement3 if statement1 is false
<?php $product_type = 'clothes'; $tax_percentage = $product_type === 'food' ? 10 : 20; var_dump($tax_percentage); // will output 20 since the condition was evaluate as false and so it return the right side value $product_price = 200; $apply_promotion = $product_price > 150 ? true : false; var_dump($apply_promotion); /* will output true, as the condition was evaluated as true and the variable received the value from the the left */
What's the output of the following script?
<?php $a = 5; $a = !$a ? 10 : 15; $a = ($a === 12) ? $a*2 : $a*3; echo $a;
Null coalescing operator
The null coalescing operator will set the value of a variable by evaluating one by one the statements separated by ??.
|Null coalescing operator||??||$a = statement1 ?? statement2||The variable $a will get the value of $statement1 if it exists and is not null, else it will get the value of $statement2|
<?php $first_name = 'Joe'; $last_name = 'Johnny'; $contact_name = $first_name ?? $last_name; echo $contact_name; /* it will output the value of $first_name, since it was defined and not null */ $book_third = 'Foundation - Asimov'; $bought_book = $book_one ?? $book_two ?? $book_third; echo $bought_book; /* will output the value of the variable $book_third, since the other two variables are not defined */
In which statements the variable $a will have the value 'php tutorial'?
<?php $x = null; $y = ''; $z = 'php tutorial';