2

I have a PHP object like below and all I want to know whats the the easiest way to get a count of objects where the property 'typeId' = 3

Array
(
 [0] => ABC Object
 (
 [id] => 13
 [typeId] => 3
 [sortOrder] => 0
 )
 [1] => ABC Object
 (
 [id] => 12
 [typeId] => 2
 [sortOrder] => 0
 )
 [2] => ABC Object
 (
 [id] => 14
 [typeId] => 4
 [sortOrder] => 0
 )
 [3] => ABC Object
 (
 [id] => 15
 [typeId] => 3
 [sortOrder] => 0
 )
)
Jonathan Leffler
760k145 gold badges962 silver badges1.3k bronze badges
asked Jun 9, 2011 at 9:55

3 Answers 3

3

A simple foreach counter should do:

$count = 0;
foreach ($array as $object) {
 if ($object->typeId == 3) $count++;
}

No need to over complicate things

answered Jun 9, 2011 at 9:58
Sign up to request clarification or add additional context in comments.

3 Comments

straight forward, I guess I should of spent a bit more time trying to solve it myself. So simple when you know how. thanks =)
blimey im looking at this old question of mine now wondering how on earth I didnt know how to do this. I guess in the last 1.5 years Ive learnt alot and cant imagine me asking something so simple anymore hehe
@SubstanceD we all have those moments
1

From my point of view, a much nicer solution is to use the array_filter function:

$newarray = array_filter( $old_array, function($object) { return $object->typeId == 3; } );

(note: inline functions only work since PHP 5.3)

answered Jun 9, 2011 at 10:48

3 Comments

This is a lot slower than using a simple foreach loop though
How can it be slower? Have you do measurements?
Thanks for your answer, I did go with the foreach loop from Petah above but I didnt know about inline functions so I've learnt something else too. nice one =)
0

Just create a temporary variable called objectCount or something similar, loop through your array and when you find an object where the typeId equals 3 add 1 to objectCount.

answered Jun 9, 2011 at 9:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.