John Davidson

PHP: Please help explain these ternary operators

0 comments
Message:


Can anyone explain this operator please? I realise its now deprecated in 7.4 so refactoring.


This example:


if ($this->interestAreas()->count() > 0) {
$ids ?: $ids = $this->interestAreas()->pluck('id');
$this->interestAreas()->detach();
}

I understand it when ?: is used assigning a variable eg: $newUser = ($user) :? null; but not as above. Can anyone explain how that may be rewritten?



My Answer:
The ternary operator in PHP is a shorthand way of writing an if-else statement. It has the following syntax:

(condition) ? value_if_true : value_if_false;

In the example you provided, the ternary operator is being used to check if the condition $this is true or false. If $this is true, the value assigned to $this is returned, otherwise, the value assigned to $that is returned.

Here is the example rewritten using an if-else statement:

if ($this) {
$result = $this;
} else {
$result = $that;
}

To refactor this code in PHP 7.4, you can simply use the null coalescing operator (??) which provides a more concise way of handling null values. Here is how you can refactor the code using the null coalescing operator:

$result = $this ?? $that;

This code does the same thing as the original ternary operator and is more readable and concise.

Rate this post

4 of 5 based on 5603 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us