azzy81
azzy81

Reputation: 2269

PHP count object property occurrences

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
        )
)

Upvotes: 2

Views: 2838

Answers (3)

smad
smad

Reputation: 1120

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)

Upvotes: 1

TJHeuvel
TJHeuvel

Reputation: 12608

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.

Upvotes: 0

Petah
Petah

Reputation: 46040

A simple foreach counter should do:

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

No need to over complicate things

Upvotes: 3

Related Questions