0

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?

Czar Pino
  • 6,258
  • 6
  • 35
  • 60
shihabudheen
  • 696
  • 8
  • 26
  • 4
    Don't do that. Ternary operators are very easy to turn into unreadable messes. Nested ones much more so. Stuck with if/else for this. It makes the code much easier to maintain. – Quentin Feb 06 '13 at 12:15
  • Retagged the question if you don't mind.. – Czar Pino Feb 06 '13 at 12:18
  • I have used the nested ternary operator inside a text box value.There feeling difficulty to maintain "if else nested loop". – shihabudheen Feb 06 '13 at 12:22
  • @MuhammedShihabudheen — That usually means you should make it a function can call it. – Quentin Feb 06 '13 at 12:28
  • @Quentin : I am using the code only once in my entire project.Is it good way to create a function for the purposes? If Yes then where should I create function? in helper or view file itself? – shihabudheen Feb 06 '13 at 12:36
  • Yes, functions are used to divide big tasks up into little tasks. Where the function goes depends on how you are structuring the project. It sounds like it might be view material. – Quentin Feb 06 '13 at 12:56

2 Answers2

2

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']));
Zathrus Writer
  • 4,311
  • 5
  • 27
  • 50
-1

As of php 7 we can use Null coalescing operator

echo $projectURL ?? $project['project_url'] ?? $project['project_id'];
Adersh
  • 598
  • 1
  • 9
  • 22