4

I am working with PHP arrays and objects. I have been working with them for quite a while now. However, I am stuck at a problem, which might have a really simple solution.

I have a variable $products inside a function which receives value on call. I am trying to count the objects in the variable to see how many products are inside it. I tried the simple count($products) and count((array)$products) function and it isn't working. I know that isn't the best way to count the objects.

Is there any way to count them?

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

I need this to return 3

object(stdClass)#20 (1) {
  ["productid"]=>
  string(2) "21"
}

I need this to return 1

2
  • 1
    It would make your life a lot easier if you used arrays of objects instead of an object containing numeric properties. How are you generating this structure and can you change it? Commented Jan 3, 2018 at 8:32
  • Create a class for these product objects and have it implement the Countable interface? Commented Jan 3, 2018 at 9:19

4 Answers 4

4

The count function is meant to be used on

Arrays Objects that are derived from classes that implement the countable interface A stdClass is neither of these. The easier/quickest way to accomplish what you're after is

$count = count(get_object_vars($products));

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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?

Comments

1

Try this: $count = sizeof(get_obj_vars($products))

Here get_obj_vars function converts the $products variable into an array and the sizeof function counts the size of array and stores it into the variable $count

Comments

0

You could do something similar to

count(get_object_vars($obj));

But it seems a bit strange to use a stdClass as an array. Why do you do that?

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.