1
$example = 
  array
    'test' =>
      array(
        'something' => 'value'
      ),
    'whatever' =>
      array(
        'something' => 'other'
      ),
    'blah' =>
      array(
        'something' => 'other'
      )
  );

I want to count how many of $example's subarrays contain an element with the value other.

What's the easiest way to go about doing this?

UserIsCorrupt
  • 4,837
  • 15
  • 38
  • 41

2 Answers2

6

array_filter() is what you need:

count(array_filter($example, function($element){

    return $element['something'] == 'other';

}));

In case you want to be more flexible:

$key = 'something';
$value = 'other';

$c = count(array_filter($example, function($element) use($key, $value){

    return $element[$key] == $value;

}));
moonwave99
  • 21,957
  • 3
  • 43
  • 64
  • This one works for me "as is", but when I try to replace "other" with a variable, it just gives me a result of 0 :/ – Alisso Oct 16 '12 at 09:37
  • 1
    This is because the lambda function is not aware of your variable - see my edit in case you want to use a var. – moonwave99 Oct 16 '12 at 10:00
1

You can try the following:

$count = 0;
foreach( $example as $value ) {
    if( in_array("other", $value ) )
        $count++;
}
Krycke
  • 3,106
  • 1
  • 17
  • 21