Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PHP isset and Null coalescing operator is throwing Notice with concatenation operator? [duplicate]

Tags:

php

php-7

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.

like image 475
Rohit Dhiman Avatar asked Sep 02 '25 13:09

Rohit Dhiman


1 Answers

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:

  1. Concatenate (.) the string sgadjgjsd with the value of $array['c'].
  2. $array['c'] does not exist, so a notice is emitted.
  3. The end result (sgadjgjsd) is then run through the null coalescing operator, and since the string is not equal to null, the string is returned (not '').
  4. The end result is assigned to a variable named $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).

like image 82
RickN Avatar answered Sep 05 '25 15:09

RickN