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.
Related
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;
I'm looking for a shorthand version of this code in PHP:
$address = isset($node->field_naam_adres['und'][0]['value']) ? $node->field_naam_adres['und'][0]['value'] : '';
Basically, I want to check if the variable is set, and if not, then return a default value.
https://stackoverflow.com/a/18603279/165330 :
before php 7 : no
$address = isset($node->field_naam_adres['und'][0]['value']) ? $node->field_naam_adres['und'][0]['value'] : '';
from php 7 : yes
$address = $node->field_naam_adres['und'][0]['value'] ?? 'default';
If you can get away with relying on truthiness and falsiness instead of the more direct isset, you can leave out the middle statement in a ternary like this:
$address = $node->field_naam_adres['und'][0]['value'] ?: '';
This works such that if the return value of the first statement evaluates as truthy, that value will be returned, otherwise the fallback will be used. You can see what various values will evaluate to as booleans here
It's important to note that if you use this pattern, you cannot wrap your initial statement in isset, empty, or any similar function. If you do, the return value from that statement simply becomes a boolean value. So while the above code will return either the value of $node->field_naam_adres['und'][0]['value'] or an empty string, the following code:
$address = isset($node->field_naam_adres['und'][0]['value']) ?: '';
Will return either TRUE or an empty string.
Currently, I check to see if a $_GET or $_POST property is set by using empty(). Like this:
$status = null;
if (!empty($_GET['foo'])) {
$status = $_GET['foo'];
}
I imagine there is an even more concise way of doing the same thing built into PHP, that like what I'm doing now with empty, also avoids printing the notice saying undefined index. Maybe something like this:
$status = something($_GET['foo']);
Or, maybe I should just ignore the notice and do:
$status = $_GET['foo'];
I'm not sure what the problem is as empty() does not generate a warning for undefined variables, but if you want it in one line, you can use a ternary expression:
$status = empty($_GET['foo']) ? null : $_GET['foo'];
How about this if you want just GET:
$status = isset($_GET['foo'])?$_GET['foo']:NULL;
Or this if you want just GET and POST:
$status = isset($_GET['foo'])?$_GET['foo']:(isset($_POST['foo'])?NULL);
You can always check if the key in the $_GET array exists and set the variable to null if it isn't. Will never throw a notive.
$status = array_key_exists('foo', $_GET) ? $_GET['foo'] : null;
You can suppress the warnings by using #.
$status = #$_GET['foo'];
Dudes,
is there a more concise way to write the statement below? If I don't check if an array key exists I get a PHP warning. However, the below is a bit too, ehm, wordy.
Thanks!
$display_flag = false;
if (array_key_exists('display_flag',$pref_array) {
$display_flag = $pref_array['display_flag'];
}
Since PHP 7 you can use the new null coalescing operator.
$display_flag = $pref_array['display_flag'] ?? false;
If $display_flag is a boolean:
$display_flag = isset($pref_array['display_flag']) && $pref_array['display_flag'];
If it's a string:
$display_flag = isset($pref_array['display_flag']) ? $pref_array['display_flag'] : false;
// Get the $pref_array from wherever
$default_prefs = array(
"display_flag" => false,
);
$pref_array = array_merge($default_prefs, $pref_array);
// Now you know it's always defined with default values
The way you have it is fine, as you should validate if the value actually exists, but you could also do a ternary op:
$display_flag = (isset($pref_array['display_flag'])) ? (bool) $pref_array['display_flag'] : false;
I typecast the contents of display_flag to bool if it is set, so you are ensured a boolean value in either case.
Also you could (but I don't recommend it), squelch the warning with the #:
$display_flag = #$pref_array['display_flag'];
Another simpler option is:
array_get($variable, 'keyName', null)
The third argument is the default value.
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']);