Вопрос

Pretty sure there's a simple answer to this but difficult to search on because of the vague terms used.

I'm using shorthand if statements and want to do more than one action when it returns true, what does the syntax look like?

For example, logically thinking I tried something like:

<?php

$var = "whatever";

(isset($var) ? $var2=$var; $var3=$var : $error="fubar");

?>

Obviously this stops with unexpected ; but hopefully you get the idea of what I'm trying to accomplish.

So sorry if this is a duplicate question, I swear I searched for it. :)

Thanks!

EDIT

I understand that whether or not shorthand is appropriate for this situation should be questioned. But still, can it be done, is the question.

Это было полезно?

Решение

Yes it's possible by using && between each assignment:

(isset($var) ? ($var2=$var) && ($var3=$var) : $error="fubar");

In the above code, if $var is set, $var2 and $var3 will get the same value, otherwise the two variables will not be changed.

That said, it is not the most appropriate method. The ternary operator should be used for simple logic, when the logic starts to get complicated, ternary is most likely no longer the best option. Instead you should just use a simple if/else.

Другие советы

For this specific instance, you can do this:

In this specific instance you can use this:

$output = (isset($var)) ? $var2 = $var3 = $var : false;

Slightly better option for this specific test instance:

$error = (isset($var)) ? !(bool)($var2 = $var3 = $var) : true;

This will set $error to true IF $var is not set, and to false if $var is set, so you could follow this up with an if($error) block.

However, ternary probably isn't the best way to approach this...

For more complicated instances you'd need to use closures or, worse, predeclared functions:

$output = (isset($var)) ? setVars($var) : false;

function setVars($var) {
    $var2 = $var3 = $var;
}

At this point, you're probably better off with if or switch statements.

As far as I know, it is not possible, and shouldn't be possible. (?:) is not, and should not be taken as a if, because it doesn't works the same way, and is not designed for it.

The ternary operator exist as a way to return a value depending of a condition, not as a "quick" if.

If you are using it without needing the return value, then you probably are using it wrong.

In this specific case, you should be using and if-else statement. It would also help making your code more readable.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top