How to write this conditional statements with ternary operators - php

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?

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

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

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

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

Shorter shorthand than ternary for setting variable to itself

I am trying to check if a variable is empty and if it is then set another variable to one string and if it's not then set the other variable to the first variable. Right now I am using a ternary operator, but I was wondering if there is an even shorter way to do this because it is setting it to a variable used in the logic.
Here is my code:
$company_name = $project->company->name;
$this->project['company_name'] = !empty($company_name)
? $company_name
: "Company";
If you have PHP 5.3+ you can use ?: but other than that no.
$this->project['company_name'] = $company_name ?: "Company";
Empty variables should evaluate to false and assign "Company".
try make a function for more variables pass values in it. you can check multiple variables using this. else i think no way to do check you to use and set other values same like (you are already using shorten)
$check = mycheck($check, 'mysting');
function mycheck($check, 'mysting') {
$return = (!empty($check) ? $check : "mysting");
return $return;
}
$this->project['company_name'] = !empty($project->company->name)
? $project->company->name
: "Company";
You can use in your function call variable=company. Then omit the ternary operator.
function xyz ($company="company") {
if ($this->project['company_name']) {
$company=$this->project['company_name'] ;
}
function even doesn't need return, depends on the usage.

Ternary Operator Inside PHP String

I want to evaluate a simple ternary operator inside of a string and can't seem to find the correct syntax.
My code looks like this:
foreach ($this->team_bumpbox as $index=>$member)
echo ".... class='{((1) ? abc : def)}'>....";
but I can't seem to get it to work properly. Any ideas on how to implement this?
You can't do it inside the string, per se. You need to dot-concatenate. Something like this:
echo ".... class='" . (1 ? "abc" : "def") . "'>....";
Well, you can do it actually:
$if = function($test, $true, $false)
{
return $test ? $true : $false;
};
echo "class='{$if(true, 'abc', 'def')}'";
I'll let you decide whether it is pure elegance or pure madness. However note that unlike the real conditional operator, both arguments to the function are always evaluated.

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it. I am looking at php.net isset code, and I see isset($_GET['something']) ? $_GET['something'] : ''
I understand normal isset operations, such as if(isset($_GET['something']){ If something is exists, then it is set and we will do something } but I don't understand the ?, repeating the get again, the : or the ''. Can someone help break this down for me or at least point me in the right direction?
It's commonly referred to as 'shorthand' or the Ternary Operator.
$test = isset($_GET['something']) ? $_GET['something'] : '';
means
if(isset($_GET['something'])) {
$test = $_GET['something'];
} else {
$test = '';
}
To break it down:
$test = ... // assign variable
isset(...) // test
? ... // if test is true, do ... (equivalent to if)
: ... // otherwise... (equivalent to else)
Or...
// test --v
if(isset(...)) { // if test is true, do ... (equivalent to ?)
$test = // assign variable
} else { // otherwise... (equivalent to :)
In PHP 7 you can write it even shorter:
$age = $_GET['age'] ?? 27;
This means that the $age variable will be set to the age parameter if it is provided in the URL, or it will default to 27.
See all new features of PHP 7.
That's called a ternary operator and it's mainly used in place of an if-else statement.
In the example you gave it can be used to retrieve a value from an array given isset returns true
isset($_GET['something']) ? $_GET['something'] : ''
is equivalent to
if (isset($_GET['something'])) {
echo "Your error message!";
} else {
$test = $_GET['something'];
}
echo $test;
Of course it's not much use unless you assign it to something, and possibly even assign a default value for a user submitted value.
$username = isset($_GET['username']) ? $_GET['username'] : 'anonymous'
You have encountered the ternary operator. It's purpose is that of a basic if-else statement. The following pieces of code do the same thing.
Ternary:
$something = isset($_GET['something']) ? $_GET['something'] : "failed";
If-else:
if (isset($_GET['something'])) {
$something = $_GET['something'];
} else {
$something = "failed";
}
It is called the ternary operator. It is shorthand for an if-else block. See here for an example http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
? is called Ternary (conditional) operator : example
What you're looking at is called a Ternary Operator, and you can find the PHP implementation here. It's an if else statement.
if (isset($_GET['something']) == true) {
thing = isset($_GET['something']);
} else {
thing = "";
}
If you want an empty string default then a preferred way is one of these (depending on your need):
$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);
If the url parameter something doesn't exist in the url then $_GET['something'] will return null
strval($_GET['something']) -> strval(null) -> ""
and your variable $value is set to an empty string.
trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)
intval() if only numeric values are expected and the default is zero. intval(null) -> 0
Cases to consider:
...&something=value1&key2=value2 (typical)
...&key2=value2 (parameter missing from url $_GET will return null for it)
...&something=+++&key2=value (parameter is " ")
Why this is a preferred approach:
It fits neatly on one line and is clear what's going on.
It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';
Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';
It's compatible with older and newer php.
Update
Strict mode may require something like this:
$str_value = strval(#$_GET['something']);
$trimmed_value = trim(#$_GET['something']);
$int_value = intval(#$_GET['somenumber']);

The use of "?" and ":"

I've read through a lot of code where they have if statements, i've noticed other languages use this to. Asp being one.
Tried googling but couldn't find a answer for it.
What exactly does ?: stand for and when to use it.
As far as I'm aware ? is equal to if() and : being equal to }else{.
It is the ternary operator (although in most languages it is better-named as the "conditional operator").
People will often erroneously refer to it as "shorthand if/else". But this is a misnomer; if/else is a statement, ?: is an expression. In most languages, these are distinct concepts, with different semantics.
This is called ternary operator.
It is meant to simplify code in some cases. Consider this:
var str;
if(some_condition)
str = 'yes';
else
str = 'no';
This can be easily rewritten as
var str = some_condition ? 'yes' : 'no';
Your assumption is right.
It is a Ternary operation (Wikipedia)
Essentially, the syntax is condition ? then-expession : else-expression. Typically it is used in assigning variables:
varname = something == 123 ? "yes" : "no";
But it can be used pretty much anywhere in place of a value. It's mostly useful for avoiding repetitive code:
if( something == 123) {
varname = "yes";
}
else {
varname = "no";
}
You could read the documentation. The section you're looking for is titled "Ternary Operator".
You can express calculations that might otherwise require an if-else construction more concisely by using the conditional operator. For example, the following code uses first an if statement and then a conditional operator to check for a possible division-by-zero error before calculating the sin function.
if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0;
s = x != 0.0 ? Math.Sin(x)/x : 1.0;
from http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.90).aspx
In Java, it's an if/else relationship.
An example of a ternary operation:
boolean bool = (x==1) ? true : false;
http://en.wikipedia.org/wiki/Ternary_operation

Simple PHP isset test

This below does not seem to work how I would expect it, event though $_GET['friendid'] = 55 it is returning NULL
<?PHP
$_GET['friendid'] = 55;
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
echo $friendid;
exit;
?>
As of PHP 7's release, you can use the null-coalescing operator (double "?") for this:
$var = $array["key"] ?? "default-value";
// which is synonymous to:
$var = isset($array["key"]) ? $array["key"] : "default-value";
In PHP 5.3+, if all you are checking on is a "truthy" value, you can use the "Elvis operator" (note that this does not check isset).
$var = $value ?: "default-value";
// which is synonymous to:
$var = $value ? $value : "default-value";
Remove the !. You don't want to negate the expression.
$friendid = isset($_GET['friendid']) ? $_GET['friendid'] : 'empty';
If you're lazy and risky, you can use error control operator # and short form of ternary operator.
$friendid = #$_GET['friendid']?: 'empty';
Currently you're working with the ternary operator:
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
Break it down to an if-else statement and it looks like this:
if(!isset($_GET['friendid']))
$friendid = $_GET['friendid'];
else
$friendid = 'empty';
Look at what's really happening in the if statement:
!isset($_GET['friendid'])
Note the exclamation mark (!) in front of the isset function. It's another way to say, "the opposite of". What you're doing here is checking that there is no value already set in $_GET['friendid']. And if so, $friendid should take on that value.
But really, it would break since $_GET['friendid'] doesn't even exist. And you can't take the value of something that isn't there.
Taking it from the start, you have set a value for $_GET['friendid'], so that first if condition is now false and passes it on to the else option.
In this case, set the value of the $friendid variable to empty.
What you want is to remove the exclamation and then the value of $friendid will take on the value of $_GET['friendid'] if it has been previously set.
The best solution for this question, i.e. if you also need to 'check for the empty string', is empty().
$friendid = empty($_GET['friendid']) ? 'empty' : $_GET['friendid'];
empty() not only checks whether the variable is set, but additionally returns false if it is fed anything that could be considered 'empty', such as an empty string, empty array, the integer 0, boolean false, ...
I am using Null coalescing operator operator in if condition like this
if($myArr['user'] ?? false){
Which is equivalent to
if(isset($myArr['user']) && $myArr['user']){
From your reply to Philippe I think you need to have a look at the differences between empty and isset.
To summarise, isset() will return boolean TRUE if the variable exists. Hence, if you were to do
$fid = $_GET['friendid'] = "";
$exists = isset($fid);
$exists will be TRUE as $_GET['friendid'] exists. If this is not what you want I suggest you look into empty. Empty will return TRUE on the empty string (""), which seems to be what you are expecting. If you do use empty, please refer to the documentation I linked to, there are other cases where empty will return true where you may not expect it, these cases are explicitly documented at the above link.
if friendid is NOT set, friendid = friendid otherwise friendid = empty
Okay, I may have been having a similar issue not being familiar with the ! situation as jasondavis had.
Kind of confusing but finding out not having the ! as in... isset($avar) compared to !isset($avar) can make quite the difference.
So with the ! in place, is more stating a YES as in
since $_GET['friendid'] = 55; has been initialized...
tell me 'no' - the opposite - that it hasn't and set it to empty.
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
where not having the ! tells me yes it has something in it, leave it be.
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
Was far less confusing with if A$="" then.... work it. ( or if $A="" for those of PHP ).
I find this use of strings and variables all as strings to be very daunting at times. Even through the confusion, I can actually understand why... just makes things a tad difficult to grasp for me.
For me, if I need to know BOTH are true
key is set
value is truthy
and if not, use another result:
the shortest way is
$result = ($arr['b'] ?? 0) ?: $arr['a'];
(ie. if b is_set AND has a real value, use it. Otherwise use a)
So in this scenario:
$arr = ['a' => 'aaa', 'b' => 'bbb'];
$result = 'aaa'

Categories