Number of objects in PHP

I work with PHP arraysand objects. I have been working with them for a long time. However, I am stuck in a problem that may have a very simple solution.

I have a variable $productsinside a function that gets a value when called. I am trying to count the objects in a variable to see how many products are inside it. I tried a simple function count($products)and count((array)$products)and it does not work. I know this is not the best way to count 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 it back 1

+4
source share
4 answers

The count function is intended for use on

, , StdClass , . / , , -

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

get_object_vars PHP, . PHP.

+3

-

count(get_object_vars($obj));

stdClass . ?

0

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

get_obj_vars $products , sizeof $count

0

. .

:

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

:

array(0 => 15);

:

array(15);

, -, , "productid"

Is there any specific reason you need to use objects?

0
source

Source: https://habr.com/ru/post/1691672/


All Articles