The count() function is used to count the elements of an array or the properties of an object. Note: For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.
Answer: Use the PHP count() or sizeof() function You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.
The problem is that count is intended to count the indexes in an array, not the properties on an object, (unless it's a custom object that implements the Countable interface). Try casting the object, like below, as an array and seeing if that helps.
$total = count((array)$obj);
Simply casting an object as an array won't always work but being a simple stdClass object it should get the job done here.
The count function is meant to be used on
A stdClass is neither of these. The easier/quickest way to accomplish what you're after is
$count = count(get_object_vars($some_std_class_object));
This uses PHP's get_object_vars function, which will return the properties of an object as an array. You can then use this array with PHP's count function.
The object doesn't have 30 properties. It has one, which is an array that has 30 elements. You need the number of elements in that array.
There is nothing wrong with count() here, "trends" is the only key that is being counted in this case, you can try doing:
count($obj->trends);
Or:
count($obj->trends['2009-08-21 11:05']);
Or maybe even doing:
count($obj, COUNT_RECURSIVE);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With