Home > database >  How to write this conditional statements with ternary operators
How to write this conditional statements with ternary operators

Time:04-18

I want to check if the usr_name of user is empty, then get his email and adjust a new variable to it.

So here is the traditional way:

if(auth()->user()->usr_name != null){
    $user_input = auth()->user()->usr_name;
}else{
    $user_input = auth()->user()->usr_email;
}

Now I want to write this with ternary condition operators, so I tried this:

$user_input = empty(auth()->user()->usr_name) ? auth()->user()->usr_name : auth()->user()->usr_email;

But this is wrong, since it returns null for $user_input.

So what is the correct way of writing this with ternary operators?

CodePudding user response:

Tenary operator check the result before "?" and if true returns first pair distinguished with ":" if not return second pair.

Let say A = true 
C = A ? 1: 2 ; 

here C equals to 1

In your example you must changed order of tenary result values

$user_input = empty(auth()->user()->usr_name) ?auth()->user()->usr_email : auth()->user()->usr_name 

CodePudding user response:

$user_input = auth()->user()->usr_name ?: auth()->user()->usr_email;

Ternary operator has a short syntax in PHP. The above code is the same as

if (auth()->user()->usr_name) {
    $user_input = auth()->user()->usr_name;
} else {
    $user_input = auth()->user()->usr_email;
}

Which is most likely equivalent to your code, considering the non strict != null check.

CodePudding user response:

You just have your logic back to front

$user_input = empty(auth()->user()->usr_name) ? auth()->user()->usr_email : auth()->user()->usr_name;

So to be clear, you are giving priority to usr_name if it is set, otherwise use the usr_email

Note that you could put this in an accessor and then call something like auth()->user()->identifier anywhere in your project

CodePudding user response:

If you use PHP >= 7.0 you could use the null-coalescing operator to write a really beautiful statement instead.

It would look something like:

$user_input = auth()->user()->usr_name ?? auth()->user()->usr_email;
  • Related