group an array based on their key

Can someone give me an idea how to group these array of fruits byt color?
 associative array ["Mango" => "Green", "Strawberry" => "Red", "Lemon" => "Green"] should return ["Green" => ["Mango", "Lemon"], "Red" => ["Strawberry"]].
Ivan EsguerraAsked:
Who is Participating?
Chris StanyonCommented:
Sure. Take a look at this:

$fruits = array(
    "Mango" => "Green",
    "Strawberry" => "Red",
    "Lemon" => "Green"

$grouped = array();

foreach ($fruits as $fruit => $color) {
    $grouped[$color][] = $fruit;


Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.