0 votes
12.1k views
in General by
How can I write a conditional statement like this?

$admin = ($user['permissions'] == 'admin') ? true;

Please note that there is no else statement. Is it possible to write this without else?

2 Answers

0 votes
by
No... ternary means three parts you need the condition, the true part, and the false part

You cannot build a ternary operator with only one expected result. Its simple Boolean logic, it just returns two values.

I would suggest you just stick with the first if/else statement you have. Besides using ternary operators can be harder to read in comparison to the standard if/else statements.

However since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

http://php.net/manual/en/language.operators.comparison.php
0 votes
by
You cannot, it requires 3 parts for that shortcut if:else

Related questions

0 votes
1 answer 1.1k views
asked Oct 29, 2021 in General by anonymous
0 votes
1 answer 1.1k views
asked Aug 19, 2016 in General by Azi Graeber
0 votes
1 answer 1.8k views
0 votes
1 answer 995 views
asked Oct 29, 2021 in General by anonymous
0 votes
1 answer 8.9k views
asked Mar 5, 2018 in General by mithun (1.3k points)
0 votes
1 answer 1.1k views
asked Jan 23, 2022 in General by Sarath
...