-1

Suppose I have an associative array like the the one below:

["dog" => "mammal", "cat" => "mammal", "snake" => "reptile"]

How to create a function in php to return an associative array grouped by its values like below:

["mammal" => ["dog", "cat"] , "reptile" => ["snake"]]
Gp Master
  • 436
  • 1
  • 4
  • 15

1 Answers1

2

Try this :

// Your array
$array = ["dog" => "mammal", "cat" => "mammal", "snake" => "reptile"];

// Create a new array
$result = array();

// Loop through your array
foreach ($array as $animal => $data) {

    // Create a key for each "animal type" and add the animal for this key
    $result[$data][] = $animal;
}

Output for var_dump($result) is :

array (size=2)
  'mammal' => 
  array (size=2)
    0 => string 'dog' (length=3)
    1 => string 'cat' (length=3)
  'reptile' => 
  array (size=1)
    0 => string 'snake' (length=5)

So now if you want a function to do this :

function getDataByKey($array) {
    $result = array();

    foreach ($array as $key => $data) {
        $result[$data][] = $key;
    }

    return $result;
}

And just do $result = getDataByKey($array); to get the same result.

Mickaël Leger
  • 3,426
  • 2
  • 17
  • 36