Skip to content
Advertisement

PHP count array keys in multidimensional array

I have a simple array like so :

stdClass Object
(
    [Colors] => Array
        (
            [0] => stdClass Object
                (
                    [value] => Blue
                )

        )

    [Sizes] => Array
        (
            [0] => stdClass Object
                (
                    [value] => 10
                )
            [1] => stdClass Object
                (
                    [value] => 30

                )

        )

)

then I just want to count array keys [Colors] and [Sizes], which should give me 2 in total, but using count() like count($array), throws "Warning: count(): Parameter must be an array or an object that implements Countable"

Advertisement

Answer

You have an object with two properties (Colors and Sizes) (https://www.php.net/manual/en/language.types.object.php).

Use get_object_vars (https://php.net/get_object_vars) to get the properties of your object, then count it:

$number_of_properties = count(get_object_vars($your_std_class_object));
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement