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.

5
  • 5
    Because PHP and JS are completely different languages based on completely different coding models. Commented Feb 23, 2019 at 20:10
  • So it write in php in short form?? Commented Feb 23, 2019 at 20:10
  • 3
    i think you mean this $id = null ?? []; Commented Feb 23, 2019 at 20:11
  • What does it mean double ??? Commented Feb 23, 2019 at 20:12
  • Note that $id is assigned false not null. See also: stackoverflow.com/questions/15327508/why-countfalse-return-1 Commented Feb 23, 2019 at 21:38

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

4
<?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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.