Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Ternary Operator multiple statements

Hello so I have a piece of code:

if($request['txt_!'] != "") {
  $randl1_1 = mt_rand(100000, 999999);
} else {
  $randl1_1 = '';
}

And when I convert it to a ternary operator:

$randl1_1 = ($request['txt_1'] != "") ? mt_rand(100000, 999999) : '';

What if I will add some in my if? Like,

if($request['txt_!'] != "") {
  $randl1_1 = mt_rand(100000, 999999);
  someFunction();
} else {
  $randl1_1 = '';
}

Is it possible in a ternary operator?

like image 308
wobsoriano Avatar asked Jun 23 '26 01:06

wobsoriano


1 Answers

It's possible, but it would make the use of a ternary less useful as it would clutter it (especially if you wanted to keep it on a single line). If you had it in the expression as the RHS, its return value would also be assigned to $randl1_1.

If someFunction() returned something truthy, then...

$randl1_1 = ($request['txt_1'] != "") ? someFunction() && mt_rand(100000, 999999) : '';

If it didn't you could use ||. But as you can see, this is ugly. If someFunction() relies on $randl1_1, well, then you have worse problems. :)

In your second case, I would use the more verbose example that you cited. You want your code to communicate to yourself and others clearly its intent.

Trying to shoehorn everything into a ternary is a bad practice.

like image 61
alex Avatar answered Jun 25 '26 17:06

alex



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!