PHP: Count a Stdclass Object

PHP: Count a stdClass object

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.

count of stdClass objects Array in php

I have solved my question by following way:

foreach ($offers as $key=> $value) 
{
echo "<br/>count->".count($value);
}

this loops itreate only once, and give me result.

Count Objects in PHP

From your example, using objects for this seems a very bloated method. Using a simple array would be much easier and faster.

This:

object(stdClass)#46 (3) {
["0"]=>
object(stdClass)#47 (1) {
["productid"]=>
string(2) "15"
}
}

Could just be this:

array(0 => 15);

Or even this:

array(15);

Your example only seems to be storing a product id, so you don't strictly need a key of "productid"

Is there any specific reason you need to use objects?

PHP: Count number of objects within another object?


count($hanap->data[0]->sections)

PHP: Count a stdClass object

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.

Why does `count(new stdClass);` return 1?

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.

Get data from stdclass Object - Count from mysql

You have made life a little difficult for yourself by not giving the result column a nice easily accessible name

If you change your query so the column has a known name like this

$park = $wpdb->get_row("SELECT COUNT(1) as count 
FROM wp_richreviews
WHERE review_status='1'");

then you have a nice easily accessible property called count

echo $park->count;


Related Topics



Leave a reply



Submit