-2

I have the following array:

$names  = array("Accounting"=>"Peter", "Finance"=>"Joe", "Human Resource"=>"Joe");

and want to output all keys and unique values.

The result should be:

Peter: Accounting

Joe: Finance, Human Resource

Thanks Philip

Philip
  • 23
  • 6
  • 2
    Possible duplicate of [How to get unique value in multidimensional array](http://stackoverflow.com/questions/10408482/how-to-get-unique-value-in-multidimensional-array) – Vasil Rashkov Jan 08 '17 at 13:37
  • @VasilShaddix amusingly enough that question is a duplicate of another question which is itself a duplicate of at least two more questions. It would be quite fun if one of those linked back to being a duplicate of this question `:-D` . A duplicate circle. – Martin Jan 08 '17 at 13:38

2 Answers2

1

Create an empty array to hold the end result and use a simple foreach loop like this;

$names  = array("Accounting"=>"Peter", "Finance"=>"Joe", "Human Resource"=>"Joe");

$resultArr = array();
foreach($names as $key => $value){
    $resultArr[$value][] = $key;
}

// display $resultArr array
var_dump($resultArr);

Here's a live demo

Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
0

Iterate through the keys and values in the array using a foreach loop and print both the keys and values.

foreach($names as $key => $value) {
 print "$key : $value\n";

}

Edmond Alosa
  • 23
  • 1
  • 5