Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;
}
share|improve this question
 
You could use array_walk. –  Waleed Khan Jul 18 '12 at 0:39
 
Is the depth always 2? –  mikemackintosh Jul 18 '12 at 0:53
 
Yes, the depth is always two –  Shawn Wernig Jul 18 '12 at 15:08
 
You might be able to skip the property_exists() if the constructor for your object creates it (meaning that the property will always exist) . . . –  ernie Jul 18 '12 at 18:23
add comment

2 Answers

up vote 2 down vote accepted

Rather than iterating through the $object array, since this is a hash, a simple check if the key/value exists/matches should work, i.e.:

if (array_key_exists($obj_key, $object)) {
    if ($object[$obj_key] == $obj_val) {
       $count++
    }
}
share|improve this answer
 
Thanks, this helped! –  Shawn Wernig Jul 18 '12 at 15:10
 
Thanks Ernie your I have solved this with your help! –  Shawn Wernig Jul 19 '12 at 2:08
add comment
if (in_array($obj_key, array_keys($objects, $obj_val))
   $count++;
share|improve this answer
1  
in_array() is a linear search, so there's likely no performance gain here. –  nickb Jul 18 '12 at 0:50
 
You've got the keys and values backward . . . –  ernie Jul 18 '12 at 0:56
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.