phpconditional-operatorshorthand-if

PHP Multiple actions in true clause in shorthand IF


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.


Solution

  • 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.