Q:

How to count objects in an array that have a certain value (PHP)

I'm using an array $timeslotlist that contains multiple "timeslot" objects.  Each timeslot has multiple values, one of which is "status".  I'm having trouble figuring out how to count the number of timeslots with a certain status.  
I'd like to do something similar to count_array_values($timeslotlist) and end with an array that has all the possible keys and the number of times they occur, but I'm running into problems because the array is filled with objects.  
I'm left with creating new arrays for each value I'm looking for, and iterating through the array with timeslots and adding those with the value I'm looking for into the new array:
$complete = array();  
$incomplete = array();  
foreach ($timeslotlist->timeslot as $timeslot) {  
    if ($timeslot->status == 'complete') {    
      $complete[]=$timeslot;  
    }  
    elseif ($timeslot->status == 'incomplete') {  
      $incomplete[] = $timeslot;  
    }  
}
$incomplete_count = count($incomplete);
$complete_count = count($complete);

Is there any quicker/simpler way to work with objects inside of an array?
Thanks for any help!

A:

You could use array_filter and pass in a anonymous function to get only the values you want.
$complete = array_filter($timeslotlist, function($slot) {
    return $slot->status == 'complete';
});

If you don't want to use array_filter and do not want to add a new condition in your foreach for every status, just turn it into a function:
function timeslot_filer($list, $status)
{
    $result = array();
    foreach($list as $slot)
        if($slot->status == $status)
            $result[] = $slot;
    return $result;
}

You can then grab all slots with a certain status by just doing
$complete = timeslot_filter($timeslotlist, 'complete');

Then it's just a matter of count($complete) to get the count.
Is this what you're looking for? If not, please let me know.

