Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to Flip Array Values to Array Keys? [duplicate]

Tags:

arrays

php

Is there a php function which can take the below array

array (size=4)
 1 => string '0' 
 6 => string '1' 
 7 => string '1' 
 8 => string '7' 

And flip it to the below array notice that an array must have unique key values so can we flip the array where value 1 = key values 6, 7

array (size=3)
 0 => string '1' 
 1 => string '6, 7'
 7 => string '8' 
like image 507
Matthew du Plessis Avatar asked Jun 11 '15 14:06

Matthew du Plessis


2 Answers

$arr = array ( 1 => '0', 6 => '1', 7 => '1', 8 => '7' );

// Find unique values of array and make them as keys
$res = array_flip($arr);
// Find keys from sourse array with value of key in new array
foreach($res as $k =>$v) $res[$k] = implode(", ", array_keys($arr, $k));

result

Array
(
    [0] => 1
    [1] => 6, 7
    [7] => 8
)
like image 54
splash58 Avatar answered Oct 16 '22 09:10

splash58


You can try it as

Simply use foreach and interchange the values of key with values

$arr = array ( 1 => '0', 6 => '1', 7 => '1', 8 => '7' );
$result = array();
foreach($arr as $key => $value){
    $result[$value][] = $key;
}
print_r($result);

FIDDLE

like image 21
Narendrasingh Sisodia Avatar answered Oct 16 '22 08:10

Narendrasingh Sisodia