Search code examples
phplaravelconditional-operatorternary

How to convert an if condition to ternary operator in PHP?


I am very new to the laravel, I am writing a normal if condition I want to convert that if condition to ternary operator ,please help me to convert it

$posts=DB::table('posts')->where('name',$id)->exists();
if($posts == false)
return $user->hasRole() ||$user->hasRights();

Solution

  • I don't use Laravel but I think it's a PHP framework, so, as documented here:

    return $posts == false ? $user->hasRole() ||$user->hasRights() : return_val_if_false
    

    You said you don't want to specify a return value if false. In that case you can simply do:

    return $posts == false && ($user->hasRole() ||$user->hasRights());
    

    This doesn't use ternary operators though, there is no way to do what you specifically want I think.