Relevant nested ternary operator in php?

I want to convert the following statement if else conditionto nested ternary.

if ($projectURL) {
    echo $projectURL;
} elseif ($project['project_url']) {
    echo $project['project_url'];
} else {
    echo $project['project_id'];
}

I wrote the following:

echo ($projectURL)?$projectURL:($project['project_url'])?$project['project_url']: $project['project_id'];

But it is found as not working properly. Is this not the right way?

0
source share
2 answers

Ternary operators are complex in PHP because they are left-associative (unlike all other languages ​​where they are right-associative). You will need to use parentheses to tell PHP what you want in this case:

echo ($projectURL ? $projectURL : ($project['project_url'] ? $project['project_url'] : $project['project_id']));
+1
source

As php 7we can use the Null Coalescence Operator

echo $projectURL ?? $project['project_url'] ?? $project['project_id'];
0
source

All Articles