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?
怪我咯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();
}
if
Don’t write judgment sentences that are too long, as this will not be easy to read;
仅有的幸福2017-05-16 12:04:33
Reference Manual
It is recommended to expand the 2 and 3 conditions in parentheses
漂亮男人2017-05-16 12:04:33
if ($article->user_id == Auth::id() && ($article->status==0 || $article->expired_at < Carbon::now()))
{
$article->delete();
return back();
}