Is it bad practice to put a ternary inside a conditional?
Consider the following code:
<?php if ((isset($hideEditButton) ? $hideEditButton : true) && $this->request->session()->read('Auth.User.id') == $user->id): ?>
<div class="hr-line-dashed"></div>
<div class="row">
<div class="col-sm-4">
<?= $this->Html->link(__('Edit Profile'), ['action' => 'account'], ['class' => 'btn btn-xs btn-primary']) ?>
</div>
</div>
<?php endif; ?>
The specific portion of the code I am concerned about is inside the conditional: (isset($hideEditButton) ? $hideEditButton : true)
Is there a better way to achieve what I am attempting to do above? I would love to know, thanks!
Yes, there is a better way to do this. Your statement
if ((isset($hideEditButton) ? $hideEditButton : true) && $this->request->session()->read('Auth.User.id') == $user->id)
could be rewritten as
if ((!isset($hideEditButton) || $hideEditButton) && $this->request->session()->read('Auth.User.id') == $user->id)
In PHP 7 you can go even further, using the null coalescing operator:
if ($hideEditButton ?? true) && $this->request->session()->read('Auth.User.id') == $user->id)
The ternary operator in this instance just makes it harder to read the condition. In my opinion, it's especially counterintuitive because you are using the literal true
in the third part of the operator; it's the opposite of where you might typically expect to see a true
result (the second spot).