1

I was wondering, is there something similar to array_count_values, but that works with objects ?

Let me explain:

array_count_values takes an array as argument, such as

[1]

Array (
    [0] => banana
    [1] => trololol
)

If i give that array to array_count_values, i will get something like:

[2]

Array (
    [banana] => 1
    [trololol] => 1
)

Now lets say that instead of strings, i have objects, that i want to count based on one of their properties. So i have:

[3]

Array (
    [0] => stdClass Object (
        [name] => banana
        [description] => banana, me gusta!
    )
    [1] => stdClass Object (
        [name] => trololol
        [description] => trolololololol
    )
)

And i'd want the magical-function-im-looking-for to count the number of objects with the same name property, returning the same input as [2]

Obviously i could easily do that on my own, but i was just wondering if there was a built-in function for that, since i couldnt seem to find one. Thanks, kind SOers!

0

3 Answers 3

5

No such function exists. You always need to first map the values you would like to count (and those values must be string or integer):

$map = function($v) {return $v->name;};

$count = array_count_values(array_map($map, $data));
Sign up to request clarification or add additional context in comments.

Comments

1

Since PHP 7.0, you can use array_column for this.

$counts = array_count_values(array_column($array_of_objects, 'name'));

When this question was originally asked and answered array_column didn't exist yet. It was introduced in PHP 5.5, but it couldn't handle arrays of objects until 7.0.

Comments

0

Check out the Reflection classes to easily fetch information about your objects dynamically.

2 Comments

The use of ReflectionClass is limited if you want to learn about properties of stdClass objects (as no properties are defined). Better use ReflectionObject or get_object_vars().
i'll give a look at that, but @hakre's answer is just what i needed. Thanks though!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.