laravel - There are "and, or" in the PHP conditional judgment at the same time. What is the priority?
習慣沉默
習慣沉默 2017-05-16 12:02:33
0
5
585

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?

習慣沉默
習慣沉默

reply all(5)
刘奇

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;

仅有的幸福

Reference Manual

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

phpcn_u1582
if(a && (b||c))
{
    $article->delete();
    return back();
}
世界只因有你

and has a priority greater than or

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template