2

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.

POV
  • 11,293
  • 34
  • 107
  • 201

3 Answers3

8

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)
IMSoP
  • 89,526
  • 13
  • 117
  • 169
3
<?php

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

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

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

Ghostff
  • 1,407
  • 3
  • 18
  • 30
0

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.

rmirabelle
  • 6,268
  • 7
  • 45
  • 42