redditor
redditor

Reputation: 4286

Counting values in array returning empty

I have an array that when printed using print_r($user_ids); outputs as:

Array ( [0] => stdClass Object ( [user_id] => 2 ) ) 

I have tried writing the following where I am trying to count how many user_ids there are, so this should print 1 but it is printing as if the array is emptry

print_r(array_count_values($user_ids));

Upvotes: 3

Views: 71

Answers (1)

Rarst
Rarst

Reputation: 2395

If you need just a total count of objects, then count() does that, as pointed out by comment.

If you specifically need to count or otherwise access user_id properties specifically (for example not object have ID) it's convenient to do that with array_column():

$user_ids = [
    (object) [ 'user_id' => 1 ],
    (object) [ 'user_id' => 2 ],
    (object) [],
];

var_dump( count( $user_ids ) ); // 3
var_dump( count( array_column( $user_ids, 'user_id' ) ) ); // 2

Upvotes: 1

Related Questions