Negated null coalescing operator (double question mark - ??) - php

I want to do this
if( !$result['success'] ?? false){
... //handle error case
But it doesn't work. Why not?
Workaround is this:
$isSuccess = $result['success'] ?? false;
if((!$isSuccess){
... //handle error case
Is there a better workaround?
Test to reproduce:
<?php
$a = [];
$x = !$a['x'] ?? 'bbb';
echo $x;
2 problems. Throws a notice. And: echos '1'

You can group the expression you're trying to negate.
if (!($result['success'] ?? false)) {
It's an operator precedence issue. The negation is of higher precedence than the null coalesce, so it is evaluated before.
So with the example $x = !$a['x'] ?? 'bbb';
We're saying "if !$a['x'] is null then 'bbb'". Well, $a['x'] is null, since it's undefined, but !$a['x'] isn't null, it is actually true (because !null === true), so the part of the expression after ?? is never evaluated.
You see 1 because that's the string representation of true.
If it was mine, I would write it instead as
if (empty($result['success'])) {
since empty will check for existence and truthiness simultaneously.

Related

Why does php return the operand rather than the condition result if you use a ?? operator on one side of the condition [duplicate]

I don't understand why this happens:
$var = 'x';
var_dump($var ?? '' == 'somevalue');
It outputs string(1) "x", while one should expect bool(false).
What is the reason behind this?
To imagine a use case, think for example at:
// I want to do something only if the optional_parameter is equal to somevalue
if($_GET['optional_parameter'] ?? '' == 'somevalue') {
...
}
It's a matter of operator precedence, try:
$var = 'x';
var_dump(($var ?? '') == 'somevalue');
More: http://php.net/manual/en/language.operators.precedence.php
Plus a general advice: there is never too many parens! :) If you're not sure what is calculated first in a given language - use them!

Operator Precedence && and?

Am I reading https://www.php.net/manual/en/language.operators.precedence.php that && binds tighter than ?? ?
Why the heck would a construct that's designed to provide a "default value" of an optional array element not bind very tightly to that element?
$ok = $ok && $someArray['optionalElement'] ?? true; // Wrong
$ok = $ok && ( $someArray['optionalElement'] ?? true ); // Right
From the PHP Docs
https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
From this, the null coalescor treats everything to it's left as an expression argument to isset()
So $ok && $someArray['optionalElement'] is taken as a full expression.
Wrapping ( $someArray['optionalElement'] ?? true ) in parentheses causes only $someArray['optionalElement'] to be the expression and so it works as you would expect.

PHP if null or false return empty array by default?

Why this line of code does not work in php like as in JS:
$id = [];
$id = null || [];
if (count($id)) {
echo 'd';
}
Why $id still is null instead empty array []? Therefore count() gives an error.
In PHP, logical operators like || always return a boolean, even if given a non-boolean output.
So your statement is evaluated as "is either null or [] truthy?" Since both null and an empty array evaluate to false, the result is boolean false.
There are however two operators which would do something similar to JS's ||:
$a ?: $b is short-hand for $a ? $a : $b; in other words, it evaluates to $a if it's "truthy", or $b if not (this is documented along with the ternary operator for which it is a short-hand)
$a ?? $b is similar, but checks for null rather than "truthiness"; it's equivalent to isset($a) ? $a : $b (this is called the null-coalescing operator)
<?php
// PHP < 7
$id = isset($id) ? $id : [];
// PHP >= 7
$id = $id ?? [];
As of PHP 7 and above
Null Coalesce Operator
Another helpful link
Watch out!
I find PHP's handling of empty to be highly questionable:
empty($unsetVar) == true (fabulous, no need to check isset as warning is suppressed!)
empty(null) == true
empty('') == true
All fine, until we get to this nonsense:
empty(false) == true. Wait, WHAT???
You've GOT to be kidding me. In no world should false be taken to mean the same thing as no value at all! There's nothing "empty" about a false assertion. And due to this logical fallacy, you cannot use empty to check ANY variable that might have a VALUE of false.
In my projects, I use a static method:
public static function hasValue($value) {
return isset($value) && !is_null($value) && $value !== '';
}
Of course, using this method, I no longer get the free warning suppression provided by empty, so now I'm also forced to remember to call the method above with the notice/warning suppression operator #:
if(self::hasValue(#$possiblyUnsetVar)) {}
Very frustrating.

PHP - Elvis Vs. Null coalesce [duplicate]

Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?
When do they behave differently and when in the same way (if that even happens)?
$a ?: $b
VS.
$a ?? $b
When your first argument is null, they're basically the same except that the null coalescing won't output an E_NOTICE when you have an undefined variable. The PHP 7.0 migration docs has this to say:
The null coalescing operator (??) has been added as syntactic sugar
for the common case of needing to use a ternary in conjunction with
isset(). It returns its first operand if it exists and is not NULL;
otherwise it returns its second operand.
Here's some example code to demonstrate this:
<?php
$a = null;
print $a ?? 'b'; // b
print "\n";
print $a ?: 'b'; // b
print "\n";
print $c ?? 'a'; // a
print "\n";
print $c ?: 'a'; // Notice: Undefined variable: c in /in/apAIb on line 14
print "\n";
$b = array('a' => null);
print $b['a'] ?? 'd'; // d
print "\n";
print $b['a'] ?: 'd'; // d
print "\n";
print $b['c'] ?? 'e'; // e
print "\n";
print $b['c'] ?: 'e'; // Notice: Undefined index: c in /in/apAIb on line 33
print "\n";
The lines that have the notice are the ones where I'm using the shorthand ternary operator as opposed to the null coalescing operator. However, even with the notice, PHP will give the same response back.
Execute the code: https://3v4l.org/McavC
Of course, this is always assuming the first argument is null. Once it's no longer null, then you end up with differences in that the ?? operator would always return the first argument while the ?: shorthand would only if the first argument was truthy, and that relies on how PHP would type-cast things to a boolean.
So:
$a = false ?? 'f'; // false
$b = false ?: 'g'; // 'g'
would then have $a be equal to false and $b equal to 'g'.
Ran the below on php interactive mode (php -a on terminal). The comment on each line shows the result.
var_export (false ?? 'value2'); // false
var_export (true ?? 'value2'); // true
var_export (null ?? 'value2'); // value2
var_export ('' ?? 'value2'); // ""
var_export (0 ?? 'value2'); // 0
var_export (false ?: 'value2'); // value2
var_export (true ?: 'value2'); // true
var_export (null ?: 'value2'); // value2
var_export ('' ?: 'value2'); // value2
var_export (0 ?: 'value2'); // value2
The Null Coalescing Operator ??
?? is like a "gate" that only lets NULL through.
So, it always returns first parameter, unless first parameter happens to be NULL.
This means ?? is same as ( !isset() || is_null() )
Use of ??
shorten !isset() || is_null() check
e.g $object = $object ?? new objClassName();
Stacking Null Coalese Operator
$v = $x ?? $y ?? $z;
// This is a sequence of "SET && NOT NULL"s:
if( $x && !is_null($x) ){
return $x;
} else if( $y && !is_null($y) ){
return $y;
} else {
return $z;
}
The Ternary Operator ?:
?: is like a gate that lets anything falsy through - including NULL
Anything falsy: 0, empty string, NULL, false, !isset(), empty()
Same like old ternary operator: X ? Y : Z
Note: ?: will throw PHP NOTICE on undefined (unset or !isset()) variables
Use of ?:
checking empty(), !isset(), is_null() etc
shorten ternary operation like !empty($x) ? $x : $y to $x ?: $y
shorten if(!$x) { echo $x; } else { echo $y; } to echo $x ?: $y
Stacking Ternary Operator
echo 0 ?: 1 ?: 2 ?: 3; //1
echo 1 ?: 0 ?: 3 ?: 2; //1
echo 2 ?: 1 ?: 0 ?: 3; //2
echo 3 ?: 2 ?: 1 ?: 0; //3
echo 0 ?: 1 ?: 2 ?: 3; //1
echo 0 ?: 0 ?: 2 ?: 3; //2
echo 0 ?: 0 ?: 0 ?: 3; //3
// Source & Credit: http://php.net/manual/en/language.operators.comparison.php#95997
// This is basically a sequence of:
if( truthy ) {}
else if(truthy ) {}
else if(truthy ) {}
..
else {}
Stacking both, we can shorten this:
if( isset($_GET['name']) && !is_null($_GET['name'])) {
$name = $_GET['name'];
} else if( !empty($user_name) ) {
$name = $user_name;
} else {
$name = 'anonymous';
}
To this:
$name = $_GET['name'] ?? $user_name ?: 'anonymous';
Cool, right? :-)
If you use the shortcut ternary operator like this, it will cause a notice if $_GET['username'] is not set:
$val = $_GET['username'] ?: 'default';
So instead you have to do something like this:
$val = isset($_GET['username']) ? $_GET['username'] : 'default';
The null coalescing operator is equivalent to the above statement, and will return 'default' if $_GET['username'] is not set or is null:
$val = $_GET['username'] ?? 'default';
Note that it does not check truthiness. It checks only if it is set and not null.
You can also do this, and the first defined (set and not null) value will be returned:
$val = $input1 ?? $input2 ?? $input3 ?? 'default';
Now that is a proper coalescing operator.
The major difference is that
Ternary Operator expression expr1 ?: expr3 returns expr1 if expr1 evaluates to
TRUE but on the other hand Null Coalescing Operator expression (expr1) ?? (expr2)
evaluates to expr1 if expr1 is not NULL
Ternary
Operator expr1 ?: expr3 emit a notice if the left-hand side
value (expr1) does not exist but on the other hand Null Coalescing Operator (expr1) ?? (expr2) In particular, does not emit a notice if the left-hand side value (expr1) does
not exist, just like isset().
TernaryOperator is left associative
((true ? 'true' : false) ? 't' : 'f');
Null Coalescing Operator is right associative
($a ?? ($b ?? $c));
Now lets explain the difference between by example :
Ternary Operator (?:)
$x='';
$value=($x)?:'default';
var_dump($value);
// The above is identical to this if/else statement
if($x){
$value=$x;
}
else{
$value='default';
}
var_dump($value);
Null Coalescing Operator (??)
$value=($x)??'default';
var_dump($value);
// The above is identical to this if/else statement
if(isset($x)){
$value=$x;
}
else{
$value='default';
}
var_dump($value);
Here is the table that explain the difference and similarity between '??' and ?:
Special Note : null coalescing operator and ternary operator is an
expression, and that it doesn't evaluate to a variable, but to the
result of an expression. This is important to know if you want to
return a variable by reference. The statement return $foo ?? $bar; and
return $var == 42 ? $a : $b; in a return-by-reference function will
therefore not work and a warning is issued.
Both of them behave differently when it comes to dynamic data handling.
If the variable is empty ( '' ) the null coalescing will treat the variable as true but the shorthand ternary operator won't. And that's something to have in mind.
$a = NULL;
$c = '';
print $a ?? '1b';
print "\n";
print $a ?: '2b';
print "\n";
print $c ?? '1d';
print "\n";
print $c ?: '2d';
print "\n";
print $e ?? '1f';
print "\n";
print $e ?: '2f';
And the output:
1b
2b
2d
1f
Notice: Undefined variable: e in /in/ZBAa1 on line 21
2f
Link: https://3v4l.org/ZBAa1
Both are shorthands for longer expressions.
?: is short for $a ? $a : $b. This expression will evaluate to $a if $a evaluates to TRUE.
?? is short for isset($a) ? $a : $b. This expression will evaluate to $a if $a is set and not null.
Their use cases overlaps when $a is undefined or null. When $a is undefined ?? will not produce an E_NOTICE, but the results are the same. When $a is null the result is the same.
For the beginners:
Null coalescing operator (??)
Everything is true except null values and undefined (variable/array index/object attributes)
ex:
$array = [];
$object = new stdClass();
var_export (false ?? 'second'); # false
var_export (true ?? 'second'); # true
var_export (null ?? 'second'); # 'second'
var_export ('' ?? 'second'); # ""
var_export ('some text' ?? 'second'); # "some text"
var_export (0 ?? 'second'); # 0
var_export ($undefinedVarible ?? 'second'); # "second"
var_export ($array['undefined_index'] ?? 'second'); # "second"
var_export ($object->undefinedAttribute ?? 'second'); # "second"
this is basically check the variable(array index, object attribute.. etc) is exist and not null. similar to isset function
Ternary operator shorthand (?:)
every false things (false,null,0,empty string) are come as false, but if it's a undefined it also come as false but Notice will throw
ex
$array = [];
$object = new stdClass();
var_export (false ?: 'second'); # "second"
var_export (true ?: 'second'); # true
var_export (null ?: 'second'); # "second"
var_export ('' ?: 'second'); # "second"
var_export ('some text' ?? 'second'); # "some text"
var_export (0 ?: 'second'); # "second"
var_export ($undefinedVarible ?: 'second'); # "second" Notice: Undefined variable: ..
var_export ($array['undefined_index'] ?: 'second'); # "second" Notice: Undefined index: ..
var_export ($object->undefinedAttribute ?: 'second'); # "Notice: Undefined index: ..
Hope this helps
Scroll down on this link and view the section, it gives you a comparative example as seen below:
<?php
/** Fetches the value of $_GET['user'] and returns 'nobody' if it does not exist. **/
$username = $_GET['user'] ?? 'nobody';
/** This is equivalent to: **/
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
/** Coalescing can be chained: this will return the first defined value out of $_GET['user'], $_POST['user'], and 'nobody'. **/
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
Essentially, using the coalescing operator will make it auto check for null unlike the ternary operator.
The other answers goes deep and give great explanations. For those who look for quick answer,
$a ?: 'fallback' is $a ? $a : 'fallback'
while
$a ?? 'fallback' is $a = isset($a) ? $a : 'fallback'
The main difference would be when the left operator is either:
A falsy value that is NOT null (0, '', false, [], ...)
An undefined variable
It seems there are pros and cons to using either ?? or ?:. The pro to using ?: is that it evaluates false and null and "" the same. The con is that it reports an E_NOTICE if the preceding argument is null. With ?? the pro is that there is no E_NOTICE, but the con is that it does not evaluate false and null the same. In my experience, I have seen people begin using null and false interchangeably but then they eventually resort to modifying their code to be consistent with using either null or false, but not both. An alternative is to create a more elaborate ternary condition: (isset($something) or !$something) ? $something : $something_else.
The following is an example of the difference of using the ?? operator using both null and false:
$false = null;
$var = $false ?? "true";
echo $var . "---<br>";//returns: true---
$false = false;
$var = $false ?? "true";
echo $var . "---<br>"; //returns: ---
By elaborating on the ternary operator however, we can make a false or empty string "" behave as if it were a null without throwing an e_notice:
$false = null;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = false;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = "";
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: ---
$false = true;
$var = (isset($false) or !$false) ? $false : "true";
echo $var . "---<br>";//returns: 1---
Personally, I think it would be really nice if a future rev of PHP included another new operator: :? that replaced the above syntax. ie:
// $var = $false :? "true"; That syntax would evaluate null, false, and "" equally and not throw an E_NOTICE...
class a
{
public $a = 'aaa';
}
$a = new a();
echo $a->a; // Writes 'aaa'
echo $a->b; // Notice: Undefined property: a::$b
echo $a->a ?? '$a->a does not exists'; // Writes 'aaa'
// Does not throw an error although $a->b does not exist.
echo $a->b ?? '$a->b does not exist.'; // Writes $a->b does not exist.
// Does not throw an error although $a->b and also $a->b->c does not exist.
echo $a->b->c ?? '$a->b->c does not exist.'; // Writes $a->b->c does not exist.
Practical short answer :
Try:
var_dump('' ?: 'ok');
vs
var_dump('' ?? 'ok');
The first one will return 'ok' if the tested value (or variable *) evaluates to false
whereas
The second one will return 'ok' if the tested value (or variable *) is null or not initialized/set.
*CAUTION : if you want to test a variable with ?:, you must first ensure it is initialized/set, otherwise PHP will raise an E_NOTICE (whereas ?? wont).
Null Coalescing operator performs just two tasks: it checks whether the variable is set and whether it is null. Have a look at the following example:
<?php
# case 1:
$greeting = 'Hola';
echo $greeting ?? 'Hi There'; # outputs: 'Hola'
# case 2:
$greeting = null;
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'
# case 3:
unset($greeting);
echo $greeting ?? 'Hi There'; # outputs: 'Hi There'
The above code example states that Null Coalescing operator treats a non-existing variable and a variable which is set to NULL in the same way.
Null Coalescing operator is an improvement over the ternary operator. Have a look at the following code snippet comparing the two:
<?php /* example: checking for the $_POST field that goes by the name of 'fullname'*/
# in ternary operator
echo "Welcome ", (isset($_POST['fullname']) && !is_null($_POST['fullname']) ? $_POST['fullname'] : 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.
# in null coalecing operator
echo "Welcome ", ($_POST['fullname'] ?? 'Mr. Whosoever.'); # outputs: Welcome Mr. Whosoever.
So, the difference between the two is that Null Coalescing operator operator is designed to handle undefined variables better than the ternary operator. Whereas, the ternary operator is a shorthand for if-else.
Null Coalescing operator is not meant to replace ternary operator, but in some use cases like in the above example, it allows you to write clean code with less hassle.
Credits: http://dwellupper.io/post/6/php7-null-coalescing-operator-usage-and-examples
When using the superglobals like $_GET or $_REQUEST you should be aware that they could be an empty string.
In this specal case this example
$username = $_GET['user'] ?? 'nobody';
will fail because the value of $username now is an empty string.
So when using $_GET or even $_REQUEST you should use the ternary operator instead like this:
$username = (!empty($_GET['user'])?$_GET['user']:'nobody';
Now the value of $username is 'nobody' as expected.
:? - means that if the first operand is true, it will return it. Otherwise, it will return the second one.
?? - evaluates if the first operand exists and is not null. If so, it returns it; otherwise, it returns its second operand.
I found an article that describes very nice the difference:
https://www.fparedes.com/blog/null-coalescing-vs-elvis-operator-php/

Assign if variable is set

In PHP I find myself writing code like this frequently:
$a = isset($the->very->long->variable[$index])
? $the->very->long->variable[$index]
: null;
Is there a simpler way to do this? Preferably one that doesn't require me to write $the->very->long->variable[$index] twice.
An update, because PHP 7 is now out and is a game-changer on this point ; the previous answers are about PHP 5.
PHP 7 solves this issue. Because you are true at saying that it is frequent to write this in PHP, and that's absolutely not elegant.
In PHP 7 comes the Null Coalesce Operator (RFC), which is a perfect shorthand for the isset ternary condition.
Its goal is to replace this type of condition:
$var = isset($dict['optional']) ? $dict['optional'] : 'fallback';
By that:
$var = $dict['optional'] ?? 'fallback';
Even better, the null coalesce operators are chainable:
$x = null;
# $y = null; (undefined)
$z = 'fallback';
# PHP 7
echo $x ?? $y ?? $z #=> "fallback"
# PHP 5
echo isset($x) ? $x : (isset($y) ? $y : $z)
The null coalesce operator acts exactly like isset() : the subject variable's value is taken if:
The variable is defined (it exists)
The variable is not null
Just a note for PHP beginners: if you use the ternary condition but you know that the subject variable is necessarily defined (but you want a fallback for falsy values), there's the Elvis operator:
$var = $dict['optional'] ?: 'fallback';
With the Elvis operator, if $dict['optional'] is an invalid offset or $dict is undefined, you'll get a E_NOTICE warning (PHP 5 & 7). That's why, in PHP 5, people are using the hideous isset a ? a : b form when they're not sure about the input.
Sadly no, because the RFC has been declined. And because isset is not a function but a language construct you cannot write your own function for this case.
Note: Because this is a language construct and not a function, it cannot be called using variable functions.
If you only assign null instead of the non set variable, you can use:
$a = #$the->very->long->variable[$index];
# makes that instruction throw no errors
Assuming you know that $the->very->long->variable is set, and you're just worried about the array index....
$x = $the->very->long->variable;
$a = isset($x[$index]) ? $x[$index] : null;
Or for a more generic variant that you can use around you code:
function array_valifset($arr,$k, $default=null) {
return isset($arr[$k]) ? $arr[$k] : $default;
}
then call it like this for any array value:
$a = array_valifset($the->very->long->variable,$index);
I stumbled across the same problem and discovered that referencing an array element does not issue a notice or warning but returns null (at least PHP 5.6).
$foo = ['bar' => 1];
var_dump($bar = &$foo['bar']); // int 1
var_dump($baz = &$foo['baz']); // null
Inside an if statement:
if($bar = &$foo['bar']) {
echo $bar;
}
if($baz = &$foo['baz']) {
echo $baz;
}

Categories