简体   繁体   中英

How can I write better code for this condition?

I want to avoid using to nested if statements

if (! is_null($user)){
    if($user->id == $currentUser->id){
       echo 'its for me';
    }else{
        echo 'its not for me';
    }
}else{
    echo 'its not for me';
}

And please note I do not want to use return statements

You can write something like this if the else in both cases it's the same.

if (!is_null($user) && $user->id == $currentUser->id){
    echo 'its for me';
} else {
    echo 'its not for me';
}

You could try something like this:

isset function and === operator makes it better.

 if (isset($user) && $user->id === $currentUser->id) {

    echo 'its for me';

 } else {

    echo 'its not for me';
 }

Hope this helps.

Peace! xD

echo 'Its' . (!is_null($user) && $user->id == $currentUser->id ? ' ' : ' not') . ' for me';

在某些条件下,三元运算符可以使if / else子句非常短。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM