Home > Software engineering >  PHP default value for variable, not working using Null coalescing operator
PHP default value for variable, not working using Null coalescing operator

Time:11-19

I, I'm using PHP 8.

I have a very short PHP code where I store a query string to a variable called $result, after that I try to set a default string value if the query value is empty, but the "??" Null coalescing operator does not work.

I solved the default value assigment with the older operation option...

Any valid reason for this behavior?

// WORK:
!empty($result['imgpath']) ? $result['imgpath'] : $result['imgpath'] = 'default.jpg';
 // WORK:
 $img_path = $result['imgpath'] ? $result['imgpath'] : $result['imgpath'] = 'default.jpg';

// DOES NOT WorK:
!empty($result['imgpath']) ?? $result['imgpath'] = 'default.jpg';
 // DOES NOT WorK:
 echo $result['imgpath'] ?? $result['imgpath'] = 'default.jpg';
 // DOES NOT WorK:
 $result['imgpath'] = $result['imgpath'] ?? 'default.jpg';

Edit: I wonder if the problem is the way I get the value, as I'm getting it from a table. The code to load the value is:

  $found = "SELECT * FROM movies WHERE $option LIKE '$text%'";
  $display = mysqli_query($conn,$found);
  while($result = mysqli_fetch_assoc($display)){
  !empty($result['imgpath']) ? $result['imgpath'] : $result['imgpath'] = 'default.jpg';
   .....
   .....

I agree with one of @Barmar's comments, it seems that the DB is sending just empty values and not null or undefined, so "??" Null coalescing operator" is not made for this kind of work...

CodePudding user response:

You don't use an explicit call to empty() when you use the null coalescing operator, because the operator does this for you.

You use the null coalescing operator when you're assigning the value somewhere else, to provide a default value for that assignment.

$img_path = $result['imgpath'] ?? 'default.jpg';
echo $img_path;

DEMO

If you want to store the result back into the original variable you're testing, you can use ??=:

$result['imgpath'] ??= 'default.jpg';
  • Related