I have an array structure that looks like this:
Array
(
[0] => Array
(
[type] => image
[data] => Array
(
[id] => 1
[alias] => test
=> no caption
[width] => 200
[height] => 200
)
)
[1] => Array
(
[type] => image
[data] => Array
(
[id] => 2
[alias] => test2
=> hello there
[width] => 150
[height] => 150
)
)
)
My question is, how can I get a count of the number of embedded arrays that have their type set as image (or anything else for that matter)? In practise this value can vary.
So, the above array would give me an answer of 2.
Thanks
The simplest way would simply be to loop over all the child arrays and check their type, incrementing a counter if it matches the required type.
If you have PHP 5.3.0 or better you could use array_reduce (untested):
Both of these could be moved into a function returning
$countwhich would allow you to specify the type to count. For example:As you can see from other answers there is far more error checking you could do, however you as you haven’t said what should be impossible (which you would want to use
assertfor).The possible errors are:
typekey setIf your array should always be set out like your example, failing silently (by putting a check in an if statement) would be a bad idea as it would mask an error in the program elsewhere.