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