PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, April 18, 2022

[FIXED] How to write this conditional statements with ternary operators

 April 18, 2022     laravel, laravel-5.8, php     No comments   

Issue

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?


Solution

$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.



Answered By - Sumit
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing