Search code examples
phpternary-operatorcoalescing

In PHP 7 how would I convert this essential ternary function for my website to coalesce?


On my website ternary operators are used all over and I'm considering trying to update them to coalesce. This is just one example and I was hoping to get tips/suggestions on making the transition. The thing with coalesce is that it sends the first value/string it finds and so I'm not sure if this is possible with coalesce?

echo (
($member_logged_in == 1)
? '<a href="profile.php">My Profile</a>'
: '<a href="login.php">Login</a>'
);

Is it possible to turn this into coalesce or should I stick with ternary operator?


Solution

  • As long as you're going to use integers or booleans to control template content, then you'll be stuck using logical statements.

    The only two alternatives are to use the ternary default operator, or write a helper function.

    // replace boolean with a string or null
    $member_logged_in = '<a href="profile.php">My Profile</a>';
    //.....
    echo $member_logged_in ?: '<a href="login.php">Login</a>';
    

    Use a logical function

    function __($a,$b,$c) { return $a ? $b : $c; }
    //........
    echo __($member_logged_in, '<a href="profile.php">My Profile</a>', '<a href="login.php">Login</a>');
    

    Ideally there shouldn't be any conditions in your templates. You could inject a variable called $menu that holds what links to display and the template should not care if the member is signed in or not.