Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP if null or false return empty array by default?

Tags:

php

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.

like image 577
OPV Avatar asked Sep 23 '26 11:09

OPV


2 Answers

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)
like image 79
IMSoP Avatar answered Sep 26 '26 02:09

IMSoP


<?php

// PHP < 7
$id = isset($id) ? $id : [];

// PHP >= 7
$id = $id ?? [];

// PHP >= 7.4
$id ??= [];

As of PHP 7 and above
Null Coalesce Operator
Another helpful link

like image 40
Ghostff Avatar answered Sep 26 '26 03:09

Ghostff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!