This question already has answers here:
Coalesce function for PHP?
(10 answers)
Closed 7 years ago.
As we know, if we are using javascript or python, we can use the below statement to get a variable, or its default.
// javascript
alert(a || 'default');
# python
print(a or 'default');
While in php, we may have to call the below:
echo $a ? $a : 'default';
And if the $a is a very long statement, the case is even worse:
echo (
we_made_many_calculation_here_and_this_is_the_result() ?
we_made_many_calculation_here_and_this_is_the_result() :
'default'
);
or
var $result = we_made_many_calculation_here_and_this_is_the_result();
echo $result ? $result : 'default';
any of the above, I think it is not neat.
And I'm blind to find any answer, to find a statement or built-in function to simplifies the work. But after trying to search many ways, I can't find the answer.
So please help.
Relating to this issue: http://php.net/manual/en/language.operators.logical.php#115208
So, see the documentation of the ternary operator, it is possible to use:
echo $a ?: 'defaults for a';
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
See: http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
Doing $a when $a is undefined will still give you an error. Unfortunately, the only proper way to do it when handling a variable is:
echo isset($a) ? $a: 'default';
When handling the long function, you still need to check for the conditions that you want to check, because if it returned false, you will still fall into default.
var $result = we_made_many_calculation_here_and_this_is_the_result(); // false
echo $result ? $result : 'default'; // echos default
You need:
var $result = we_made_many_calculation_here_and_this_is_the_result();
echo !is_null($result) ? $result : 'default';
This is a sad limitation in what php interprets as false. You can see a full list here.
Why not try doing it the other way round, and start off by setting the variable to its default value?
$a = "default";
...
echo $a;
Then you don't need to check if it's set or not - just use the variable.
This has the added bonus of it then preventing the (unfortunately very common, and potentially tricky to track down) problem of using an unassigned variable.
Related
In PHP, if I have a ternary like this:
$my_thing = $this->myAttribute ? $this->myAttribute : "No attribute was set.";
can it be abbreviated like this?
$my_thing = $this->myAttribute ?: "No attribute was set."
I thought I remembered PHP supporting this in its ternaries, but now I'm getting an error.
It's supported in PHP 5.3 and up. From PHP.net
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
Since PHP 5.3, it is possible to leave out the middle part of the
ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1
evaluates to TRUE, and expr3 otherwise.
Is there any better or more concise way than following code to set default value of variables?
$v = isset($v) ? $v : "default value";
TL;DR - No, that expression can't be made any shorter.
What you want is for the shortened ternary expression to perform an implicit isset(). This has been discussed on the mailing list and an ifsetor RFC has been created that covers the concept as well.
Since the shortened ternary operator already existed at the time of the above discussion, something like this was proposed using a non-existent operator ??:
// PROPOSAL ONLY, DOES NOT WORK
$v = $v ?? 'default value';
Assign 'default value' if $v is undefined.
However, nothing like this has been implemented in the main language to date. Until then, what you have written can't be made any shorter.
This horrible construct is shorter, but note that it's not the same because it assigns the default value if the variable exists but evaluates to false:
// DO NOT USE
$v = #$v ?: 'default value';
Here is a shorter syntax:
isset($v) || $v="default value";
Just asked this and was pointed here. So in case you use a key of an array, this might be an improvement
function isset_get($array, $key, $default = null) {
return isset($array[$key]) ? $array[$key] : $default;
}
Nope. That's the right way if you don't really know whether $v is set.
No way.If you use ternary operator.
In JavaScript I have a habit of using the following fallback evaluation
var width = parseInt(e.style.width) || e.offsetWidth() || 480
meaning width will get the last non-zero (non-null...) value
However, in php I can't write
$a = $_GET['id'] || 1;
I have to write so
$a = $_GET['id']?$_GET['id']:1;
Which is bad because $_GET['id'] is evaluated twice
Any suggestions?
If you have PHP 5.3 you can simply do:
$a = $_GET['id'] ?: 1;
As from the PHP manual:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
If you don't have PHP 5.3 or greater you would have to use Sarfraz's (or better, delphist's) suggestion. However, in larger applications I tend to have the request variables wrapped in a way that I can specify a default value in the argument to the function retrieving the request. This has the advantage that it is cleaner (easier to understand) and it doesn't generate warnings if the index doesn't exist in the $_GET variable as I can use things like isset to check if the array index exists. I end up with something like:
its better to be
$a = isset($_GET['id']) ? $_GET['id'] : 1;
Unfortunately PHP doesn't support that syntax. The best you can do is to use ternary operator like your example:
$a = $_GET['id'] ? $_GET['id'] : 1;
The only option coming in mind for the equivalent stuff is that of using Switch condition.
Array lookup in a single array is such a marginal amount of time that it really doesn't make a difference.
If you're cascading down a number of arrays, it would be faster to store the value in a temp variable:
$tempId = $example['this']['is']['an']['example']['where']['it\'s']['worth']['storing'];
$a = $tempId ? $tempId : 1;
Otherwise $a = $_GET['id'] ? $_GET['id'] : 1; is just fine.
PHP 5.3 supports the following syntax:
$a = $_GET['id'] ?: 1;
From the documentation:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
I use the ternary operator quite often but I've not been able to find anything in the documentation about this and I've always wondered it.
The following is a possible example:
echo ($something->message ? $something->message : 'no message');
as you can see, if $something->message is correct, we return $something->message, but why write it twice? Is there a way to do something like:
echo ($something->message ? this : 'no message');
Now I'm not well versed in programming theory, so it's possible that there is a reason that the former cannot be referenced with something like "this" but why not? Would this not stream line the use of the ternary operator? For something like my example it's pretty useless, but let's say it's
echo (function(another_function($variable)) ? function(another_function($variable)) : 'false');
I'm unable to find any way to do this, so I'm assuming it's not possible, if I'm wrong please inform me, otherwise: why not? Why is this not possible, what's the technical reason, or is it just something that never happened? Should I be declaring it as a variable and then testing against that variable?
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
Source
For example
$used_value = function1() ?: $default_value;
Is the same as
$check_value = function1(); //doesn't re-evaluate function1()
if( $check_value ) {
$used_value = $check_value;
} else {
$used_value = $default_value;
}
Word for the wise
If your going to be depending on typecasting to TRUE it's important to understand what WILL typecast to TRUE and what won't. It's probably worth brushing up on PHP's type juggling and reading the type conversion tables. For example (bool)array() is FALSE.
In PHP, is there a way to simplify this even more, without using an if()?
$foo = $bar!==0 ? $foo : '';
I was wondering if there was a way to not reassign $foo to itself if the condition is satisfied. I understand there is a way to do this in Javascript (using &&, right?), but was wondering if there was a way to do this in PHP.
In PHP 5.3 the short form of the ternary operator has finally arrived, so you can do the following.
$foo = $bar ?: '';
See the Comparison Operators section - "Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise."
Yup, you can use the logical and (&&) operator in PHP as well.
$bar === 0 && $foo = '';