"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Count Properties of a stdClass Object Accurately in PHP?

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

Published on 2024-11-02
Browse:613

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

Counting Properties of a stdClass Object in PHP

Counting the properties of a stdClass object in PHP using the count() function may not always return the expected result. The count() function is primarily designed to count the elements of an array.

To accurately count the properties of a stdClass object, you can cast it into an array using (array)$obj. This conversion will create an array with keys and values corresponding to the object's properties.

Example

Consider the following stdClass object, which represents daily trend data retrieved from Twitter:

$trends = json_decode('{
    "trends": {
        "2009-08-21 11:05": [
            {
                "query": "Follow Friday",
                "name": "Follow Friday"
            },
            ... // Additional trend data
        ]
    }
}');

If you use count($trends) on this object, you may not get the expected result of 30, as the object has 30 properties.

Instead, cast the object to an array and then count the elements:

$total = count((array)$trends);

This approach will accurately count the properties of the $trends object, resulting in the correct value of 30.

Remember that casting an object as an array can have limitations in certain circumstances. However, for simple stdClass objects like the one in this example, it provides a convenient method for counting their properties.

Release Statement This article is reproduced at: 1729348874 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3