Count specific values in multidimensional array
PHP has no support for a SQL where
sort of thing, especially not with an array of arrays. But you can do the counting your own while you iterate over the data:
$count = array();
foreach($fruit as $one)
{
@$count[$one['color']]++;
}
printf("You have %d green fruit(s).\n", $count['green']);
The alternative is to write yourself some little helper function:
/**
* array_column
*
* @param array $array rows - multidimensional
* @param int|string $key column
* @return array;
*/
function array_column($array, $key) {
$column = array();
foreach($array as $origKey => $value) {
if (isset($value[$key])) {
$column[$origKey] = $value[$key];
}
}
return $column;
}
You then can get all colors:
$colors = array_column($fruit, 'color');
And then count values:
$count = array_count_values($colors);
printf("You have %d green fruit(s).\n", $count['green']);
That kind of helper function often is useful for multidimensional arrays. It is also suggested as a new PHP function for PHP 5.5.
$number_of_green_fruit = 0;
for ($row = 0; $row < 3; $row++) {
if($fruit[$row]["color"]=="green") {
$number_of_green_fruit++;
echo $fruit[$row]["name"] . '<br />';
}
}
All you need is an extra counter:
for ($row = $number_of_green_fruit = 0; $row < 3; $row++) {
if($fruit[$row]["color"]=="green") {
echo $fruit[$row]["name"] . '<br />';
$number_of_green_fruit++;
}
}
if($number_of_green_fruit > 1) {
echo "You have more than 1 piece of green fruit";
}