I have this function, which iterates through an array of objects in search of matching key => value pairs. I'm curious if there isn't an easier (or more graceful) way:
function count_class_attr($objects, $obj_key, $obj_val) {
$count = 0;
foreach ($objects as $object ) {
foreach ($object as $key => $value) {
if ($key == $obj_key && $value == $obj_val){
$count ++;
}
}
}
return $count;
}
I think below is closer to what I was looking for. I was looping through an array of objects, not an array of arrays - would the function below be as efficient as possible?
function count_class_attr($objects, $obj_key, $obj_val) {
$count = 0;
foreach ($objects as $object ) {
if (property_exists($object, $obj_key)) {
if($object->$obj_key == $obj_val) { $count ++; }
}
}
return $count;
}
array_walk
. – Waleed Khan Jul 18 '12 at 0:39