corresponding nested ternary operator in php?

风流意气都作罢 提交于 2019-11-26 12:49:19

问题


I want to convert following if else condition to nested ternary operator.

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

I have written like following.

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

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


回答1:


Ternary operators are tricky thing in PHP, as they are left-associative (unlike all other languages, where it's right-associative). You will need to use parenthesis to tell PHP what you want exactly in this case:

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



回答2:


As of php 7 we can use Null coalescing operator

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


来源:https://stackoverflow.com/questions/14728810/corresponding-nested-ternary-operator-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!