Search code examples
phparraysgroupingpreserve

Group associative array elements by values and preserve original keys as new values in each group


I want to be able to group Associative Arrays with their `keys. So far I'm lost of what syntax to use.

As of now, I have thus code,

$associativeArray = array("Ripe Mango"=>"Yellow", "Strawberry"=>"Red", "Lemon"=>"Yellow");
groupByColor($associativeArray);

function groupByColor($groupedArray)
{
  return $groupedArray;
}

My goal is to return the array while having it grouped, the ideal result will be like this;

["Yellow"=>["Ripe Mango", "Lemon"], "Red"=>["Strawberry"]]

Any hints on what method to use?


Solution

  • Inside function do foreach()

    <?php
    
    $associativeArray = array("Ripe Mango"=>"Yellow", "Strawberry"=>"Red", "Lemon"=>"Yellow");
    
    function groupByColor($associativeArray){
        $final_array = [];
        foreach($associativeArray as $key=>$val){
            $final_array[$val][] = $key;
        }
    
       return $final_array;  
    }
    print_r(groupByColor($associativeArray));
    

    Output:- https://eval.in/933011

    Note:- you can assign groupByColor($associativeArray) returned array to a new variable and print that variable like below:-

    $color_array = groupByColor($associativeArray);
    print_r($color_array);