3

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));
1
  • 4
    if you don't want the unique count you just can do count($array) Commented Sep 27, 2017 at 14:05

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.