-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

2
  • 2
    Possible duplicate of How to get unique value in multidimensional array Commented Jan 8, 2017 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. Commented Jan 8, 2017 at 13:38

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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";

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.