-2

How does count(false) === 1 make any sense at all since count(null) === 0?

count — Count all elements in an array, or something in an object. -http://php.net/manual/en/function.count.php

This makes even less sense since booleans are primitives and not arrays or countables.

max
  • 96,212
  • 14
  • 104
  • 165
  • And that's just how it was defined: https://github.com/php/php-src/blob/master/ext/standard/array.c#L285 – mario Nov 02 '14 at 18:33

1 Answers1

1

count returns the number of elements. false is one element (a boolean) but null is nothing, null is not a value.

Note that you can destroy a variable, for example an item in an array by setting it to null:

$a = array(1,2,3);
$a[1] = null;
var_dump(isset($a[1]));

You will obtain false because $a[1] is no longer defined.

If you do the same with false:

$a = array(1,2,3);
$a[1] = false;
var_dump(isset($a[1]));

You will obtain true because $a[1] is set to the boolean false

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • 1
    Actually if you read the source of `count()` that @mario posted than anything that is not null, an array or object returns 1. Which is just plain weird for a function that preparedly counts arrays and countable objects. Your example is a completely different case, $a is actual array. `FALSE` is a primitive boolean value - not a element of an array. An example of this would be if you have a function `get_rows_from_db` that gets a number of rows from the database or returns false if the query fails. You would expect `if (count(get_rows_from_db())) {}` to be sufficient... – max Nov 02 '14 at 19:57
  • instead of if (is_array($result) && count($result)). Even returning -1 would make more sense. – max Nov 02 '14 at 19:59