search

Home  >  Q&A  >  body text

laravel - There are "and, or" in the PHP conditional judgment at the same time. What is the priority?

There are "and, or" in the PHP conditional judgment at the same time. What is the priority?

For example:

if ($article->user_id ==  Auth::id() && $article->status==0 || $article->expired_at < Carbon::now())
{
    $article->delete();
    return back();
}

There are 3 conditions in the if statement:

$article->user_id ==  Auth::id()      //文章属于该登录用户
$article->status==0                   //文章的status字段为0
$article->expired_at < Carbon::now()  //文章已过期

What I want to express is that the first condition must be met, and only one of the second and third conditions must be met.

The question is how to write this conditional statement. Is it correct to write it like in the above if() code?

習慣沉默習慣沉默2827 days ago607

reply all(5)I'll reply

  • 怪我咯

    怪我咯2017-05-16 12:04:33

    According to the PHP Manual: Operator Priority page, the priority is > ;

    So the code of the subject can be written like this:

    $isAuthor = $article->user_id ==  Auth::id();
    $isValid = $article->status==0 || $article->expired_at < Carbon::now();
    
    if ($isAuthor && $isValid)
    {
        $article->delete();
        return back();
    }

    ifDon’t write judgment sentences that are too long, as this will not be easy to read;

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-16 12:04:33

    Reference Manual

    It is recommended to expand the 2 and 3 conditions in parentheses

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-16 12:04:33

    if(a && (b||c))
    {
        $article->delete();
        return back();
    }

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-16 12:04:33

    and has a priority greater than or

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-16 12:04:33

    if ($article->user_id ==  Auth::id() && ($article->status==0 || $article->expired_at < Carbon::now()))
    {
        $article->delete();
        return back();
    }
    
    

    reply
    0
  • Cancelreply