11

I'm trying to count the number of times a certain value appears in my multidimensional array based on a condition. Here's an example array;

$fruit = [
    "oranges" => [
        "name"    => "Orange",
        "color"   => "orange",
        "taste"   => "sweet",
        "healthy" => "yes"
    ],
    "apples" => [
        "name"    => "Apple",
        "color"   => "green",
        "taste"   => "sweet",
        "healthy" => "yes"
    ],
    "bananas" => [
        "name"    => "Banana",
        "color"   => "yellow",
        "taste"   => "sweet",
        "healthy" => "yes"
    ],
    "grapes" => [
        "name"    => "Grape",
        "color"   => "green",
        "taste"   => "sweet",
        "healthy" => "yes"
    ]
];

If I want to display all green coloured fruit, I can do the following (let me know if this is the best way of doing it):

for ($row = 0; $row < 3; $row++) {
    if($fruit[$row]["color"]=="green") {
         echo $fruit[$row]["name"] . '<br />';
    }
}

This will output:

Apple
Grape

That's great and I can see their are 2 values there, but how can I actually get PHP to count the number of fruit where the colour is green and put it in a variable for me to use further down the script to work stuff out?

I want to do something like;

if ($number_of_green_fruit > 1) {
    echo "You have more than 1 piece of green fruit";
}

I've taken a look at count(), but I don't see any way to add conditional logic to that function call.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
user1221488
  • 175
  • 1
  • 2
  • 7

4 Answers4

13

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
10
$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 />';
    }
}
Blaster
  • 9,414
  • 1
  • 29
  • 25
  • In modern PHP versions, you can use array destructuring inside of a `foreach()` loop like [this](https://3v4l.org/oI5jn). – mickmackusa Apr 16 '23 at 03:27
5

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";
}
DaveRandom
  • 87,921
  • 11
  • 154
  • 174
1

With PHP 5.4+ you can have this short snippet to count specific values (don't even need to declare the $count variable previously)

array_walk_recursive($fruit, function ($value) use (&$count) {
    $count += (int) ($value === 'green');
});

var_dump($count); // Outputs: int(2)
dmmd
  • 2,938
  • 4
  • 33
  • 41