I have read that PHP isset and null coalescing operator used to ignore PHP Notice: Undefined index:
I have seen this post also PHP ternary operator vs null coalescing operator
But I am getting PHP notice with both of them while using them with string concatenation operator:
<?php
$array = ['a'=>'d'];
$c = $array['c'] ?? '';
$d = isset($array['c']) ? $array['c'] : '';
$val = "sgadjgjsd".$array['c'] ?? ''; // PHP Notice: Undefined index: c in /home/cg/root/986045/main.php on line 6
$val2 = "sgadjgjsd".isset($array['c']) ? $array['c'] : ''; // PHP Notice: Undefined index: c in /home/cg/root/986045/main.php on line 7
?>
EDIT:
I know This can be solved by the following methods
1) assigning to variable like
$val = "sgadjgjsd".$c = $array['c'] ?? '';
2) using @
$val = "sgadjgjsd".@$array['c'] ?? '';
3) adding brackets (and as Karsten suggested )
$val = "sgadjgjsd".($array['c'] ?? '');
But I am looking for the reason behind it.
Every operator has its own 'importance' (operator precedence, as @Karsten-koop pointed out) which dictates in what order they are executed. For example:
echo 10 + 5 * 3; // 25 (10+15), not 45 (15×3)
In this case:
$val = "sgadjgjsd".$array['c'] ?? '';
PHP will do the following steps:
sgadjgjsd
with the value of $array['c']
.$array['c']
does not exist, so a notice is emitted.sgadjgjsd
) is then run through the null coalescing operator, and since the string is not equal to null, the string is returned (not ''
).$val
.So why does 10 + 5 * 3 equal 25? Look up the *
and +
operators in the table on the linked page. Notice that *
is higher up in the list, so it goes first.
For the other example, the concatenation opereator .
is (quite a bit) higher up than ??
.
Using brackets is the proper solution; they allow you to specify what goes first:
echo (10 + 5) * 3;
$val = "sgadjgjsd".($array['c'] ?? '');
// Does ?? first and returns either the value of $array['c'] or ''
// and only then it does the string concatenation and assignment to $val.
http://php.net/manual/en/language.operators.precedence.php
Side-note: You might recognise this same concept from school because the same thing exists in mathematics (some historical background on why).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With