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
azzy81
2,2892 gold badges26 silver badges37 bronze badges
3 Answers 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
Petah
46.2k30 gold badges161 silver badges217 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
azzy81
straight forward, I guess I should of spent a bit more time trying to solve it myself. So simple when you know how. thanks =)
azzy81
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
Petah
@SubstanceD we all have those moments
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
smad
1,1201 gold badge15 silver badges30 bronze badges
3 Comments
Petah
This is a lot slower than using a simple
foreach loop thoughsmad
How can it be slower? Have you do measurements?
azzy81
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 =)
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
TJHeuvel
12.6k4 gold badges40 silver badges46 bronze badges
Comments
lang-php