Search code examples
phpmultidimensional-arrayfilteringcounting

Display and count qualifying data from a 2d array


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.


Solution

  • $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 />';
        }
    }