Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 460
Joe Avatar asked Dec 12 '25 21:12

Joe


2 Answers

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.

like image 189
MrCode Avatar answered Dec 15 '25 12:12

MrCode


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.

like image 33
Glitch Desire Avatar answered Dec 15 '25 12:12

Glitch Desire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!