Shane Stillwell
Shane Stillwell

Reputation: 3248

Is there an efficient way to write this PHP if / else statement?

I've written a simple issue tracker for my web app. I have some comments that I want to keep private (only a role of 'root' can see them). Is there a better way to write the following so I do not need the empty else section?

$role will be 'root' or some other values
$is_private will be true if the comment is private

<?php
// Don't show private comments to non-root users
if ($is_private && 'root' != $role):
    // NON Root cannot see private
else:
?>
<div class="comment <?= $is_private ? 'private' : '' ; ?>">
    <div class="comment-meta toolbar">
    <?= $is_private ? 'PRIVATE - ': ''; ?>
    <span class="datestamp"><?= $created_at; ?></span> - 
    <span class="fullname"><?= $fname . ' ' . $lname; ?></span></div>
    <p class="content"><?= nl2br($body); ?></p>

</div>
<?php endif; ?>

Upvotes: 0

Views: 242

Answers (5)

carlpett
carlpett

Reputation: 12583

This might be wrong, see discussion

if ($is_private && 'root' == $role):

Upvotes: 0

Patrick
Patrick

Reputation: 3172

by better I'm assuming you mean cleaner code?

if so, put it in a function and call it.

function showPrivateComment($is_private, $role)
{
    if($is_private && $role == 'root')
        return true;
    elseif(!$is_private)
        return true;

    return false;
}

Upvotes: -1

Abdullah Jibaly
Abdullah Jibaly

Reputation: 54780

if (!$is_private || 'root' == $role):

Upvotes: 1

Michael Madsen
Michael Madsen

Reputation: 54989

All you need to do is to invert the condition: comments are visible if they are NOT private, or if $role is 'root'.

<?php
// Don't show private comments to non-root users
if (!$is_private || 'root' == $role):
?>
<div class="comment <?= $is_private ? 'private' : '' ; ?>">
    <div class="comment-meta toolbar">
    <?= $is_private ? 'PRIVATE - ': ''; ?>
    <span class="datestamp"><?= $created_at; ?></span> - 
    <span class="fullname"><?= $fname . ' ' . $lname; ?></span></div>
    <p class="content"><?= nl2br($body); ?></p>

</div>
<?php endif; ?>

Upvotes: 3

Gumbo
Gumbo

Reputation: 655129

You could simply invert the whole expression:

if (!($is_private && 'root' != $role))

Or you solve it using De Morgan’s laws to this:

    !($is_private && 'root' != $role))
<=>  !$is_private || !('root' != $role)
<=>  !$is_private || 'root' == $role

Upvotes: 2

Related Questions