5

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' 

3 Answers3

11
$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
)
splash58
  • 26,043
  • 3
  • 22
  • 34
4

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

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
3

No, there is not an existing, but you can write your's custom as per need, see the below function does exact what you need:

function customFlip($arr){
    $newArray = array();
    if (is_array($arr)) {
        foreach ($arr as $key => $value) {
            if (array_key_exists($value, $newArray)) {
                if (empty($newArray[$value])) {
                    $newArray[$value] = $key;
                } else {
                    $newArray[$value] .= ','.$key;
                }
            } else {
                $newArray[$value] = $key;
            }
        }
        return $newArray;
    }
    return false;
}
kamal pal
  • 4,187
  • 5
  • 25
  • 40