PHP - Counting matching arrays in an array
I have an array structure that looks like this:
Array
(
[0] => Array
(
[type] => image
[data] => Array
(
[id] => 1
[alias] => test
[caption] => no caption
[width] => 200
[height] => 200
)
)
[1] => Array
(
[type] => image
[data] => Array
(
[id] => 2
[alias] => test2
[caption] => hello there
[width] => 150
[height] => 150
)
)
)
My question is, how can I get the number of inline arrays that have their own type, given as an image (or something else for that matter)? In practice, this value can vary.
So the above array would give me an answer of 2.
thanks
a source to share
The easiest way is to just loop over all child arrays and check their type, incrementing the counter if it matches the type you want.
$count = 0;
foreach ( $myarray as $child ){
if ( $child['type'] == 'image' ){
$count++;
}
}
If you have PHP 5.3.0 or higher, you can use array_reduce (untested):
$count = array_reduce($myarray,
function($c, $a){ return $c + (int)($a['type'] == 'image'); },
0
);
Both of these can be moved into a return function $count
that will allow you to specify the type to count. For instance:
function countTypes(array $haystack, $type){
$count = 0;
foreach ( $haystack as $child ){
if ( $child['type'] == $type ){
$count++;
}
}
return $count;
}
As you can see from the other answers, you can make a lot more mistakes, but you like you didn't say that it should be impossible (what you would like to use assert
for).
Possible mistakes:
- Child is not an array
- The child has a set
type
If your array should always be specified as your example, unsuccessful silence (by putting a check in an if statement) would be a bad idea, as it would mask a program error elsewhere.
a source to share
Try the following:
function countArray(array $arr, $arg, $filterValue)
{
$count = 0;
foreach ($arr as $elem)
{
if (is_array($elem) &&
isset($elem[$arg]) &&
$elem[$arg] == $filterValue)
$count++;
}
return $count;
}
In your example, you would call it like this:
$result = countArray($array, 'type', 'image');
a source to share