How to Accurately Count Properties of a stdClass Object in PHP?

Patricia Arquette
Release: 2024-10-19 22:47:02
Original
622 people have browsed it

How to Accurately Count Properties of a stdClass Object in PHP?

Counting the Properties of a stdClass Object in PHP

When working with objects created from JSON data using json_decode, you might encounter an issue where the count() function returns an incorrect value despite the object having numerous properties.

The Issue

Consider the following example:

[trends] => stdClass Object
    (
        [2009-08-21 11:05] => Array
            (
                [0] => stdClass Object
                    (
                        [query] => "Follow Friday"
                        [name] => Follow Friday
                    )

                ...
                [19] => stdClass Object
                    (
                        [query] => H1N1
                        [name] => H1N1
                    )

            )
     )
Copy after login

Running count($obj) on this object would return 1, even though there are 30 properties. This is because count() is designed to count the number of indexes in an array, not the properties of an object.

The Solution

To resolve this issue, cast the object to an array like so:

$total = count((array)$obj);
Copy after login

Casting the object as an array forces count() to evaluate the number of properties instead of indexes. In this example, $total would accurately reflect the count of 30 properties.

Note

This casting technique may not always be applicable. However, for simple stdClass objects like the one provided, it should suffice to obtain the correct property count.

The above is the detailed content of How to Accurately Count Properties of a stdClass Object in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!