Hussein
Hussein

Reputation: 53

How to get the number of keys in a php object

I have an arrays object whith one key user, and i try to get the size of this key, the sizeOf function return 6. But if i have more than one key user in my object then sizeOf return the number of key user.

Here is an exemple of my object :

object(Context)[347]
protected 'values' => 
array (size=23)
  [...]
  'user' => 
    array (size=6)
      'nom' => 
        array (size=2)
          '@content' => string 'foo' (length=6)
          '@attributes' => 

      'email' => string '[email protected]' (length=24)
  [...]

What the best way to get the number of user key in my object ?

Thanks

EDIT:

With multiple users i got this

object(Context)[347]
protected 'values' => 
array (size=23)
  [...]
  'user' => 
    array (size=2)
      0 => 
        array (size=6)
          'nom' => 
            array (size=2)
              '@content' => string 'foo' (length=6)
          'email' => string '[email protected]' (length=24)
      1 => 
        array (size=6)
          'nom' => 
            array (size=2)
              '@content' => string 'bar' (length=6)
          'email' => string '[email protected]' (length=24)

Upvotes: 4

Views: 3684

Answers (2)

Wissam El-Kik
Wissam El-Kik

Reputation: 2525

There's no function to count the elements in an object.

There's a hack: You can cast the object as an Array:

$arr = (array)$obj;
$count = count($arr);

You can also use the following if you're using a STD Class Object:

$arr = get_object_vars($some_std_class_object);
$count = count($arr);

I didn't understand what you the OP means by "number of user key", but once you get the Array, you can easily retrieve the count of any element in this Array.

Upvotes: 1

Sougata Bose
Sougata Bose

Reputation: 31749

Try with -

echo count(array_keys((array)$yourObject));

For multiple users -

$count = 0;
foreach((array)$yourObject as $value) {
    $count++;
}
echo $count;

Upvotes: 3

Related Questions