0

stdClass in PHP should be an empty object, but it's count() is 1 for some reason. Why?

PHP> (array)(new stdClass);
// array(
// 
// )
PHP> empty(new stdClass);
// false
PHP> count(new stdClass);
// 1
kero
  • 10,647
  • 5
  • 41
  • 51
kolypto
  • 31,774
  • 17
  • 105
  • 99

2 Answers2

8

If you read the documentation of the count function, you'll find this section about the return value:

Return Values

Returns the number of elements in array_or_countable. If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.

gpgekko
  • 3,506
  • 3
  • 32
  • 35
  • Good find! Anybody still believes that JS is a surprising language..? :) – kolypto Jun 03 '14 at 11:35
  • @kolypto But you asked a PHP question.... ? – Oliver Spryn Jun 03 '14 at 11:36
  • @spryno724, sure, just noticing that PHP is also surprising sometimes – kolypto Jun 03 '14 at 11:38
  • @kolypto If there is one skill I learned from working in JS, it's the ability to scan/read documentation fast and efficient... :P – gpgekko Jun 03 '14 at 11:39
  • 1
    @kolypto But why should this be surprising? [See this list](http://3v4l.org/03oXJ) - the output is more or less making sense. You get 0 for `NULL` or something countable and empty and 1 otherwise, because you always have 1 string, 1 boolean, and here: 1 object. – kero Jun 03 '14 at 11:42
  • 1
    @kingkero, well, passing an empty object, I expected count() to tell that it's empty. 10 years in PHP, and learning never stops .. :) – kolypto Jun 03 '14 at 11:48
2

An object passed to count() needs to implement the Countable interface.

echo count(new stdclass()); //outputs 1

class countIt implements Countable{
    public function count(){        
    }
}

echo count(new countIt()); //outputs 0

See Countable for more details.

Alex
  • 335
  • 2
  • 11