0

I have an array:

$input = array(1,2,3,4,6,5,3,6)

and I want the key/value pairs to be flipped. This can be done by using the array_flip() function. $flipped = array_flip($input)

If in the original array has 2 or more same values (in this case number 6)how can I return it in an array?

array= ([1]=0,[2]=>1,[4]=>2,[6]=>array(3,6),[5]=>4,[3]=>5)

I tried to use array_count_values() but can't figure out how to do it?

Roman
  • 1,118
  • 3
  • 15
  • 37
  • 1
    http://stackoverflow.com/a/30795697/2899618 – Narendrasingh Sisodia Aug 20 '15 at 13:35
  • What you are saying is that you want the result to be an array where the keys are the unique items found in the input array and the values for each key are the position(s) where they appear in the original array? – Josh J Aug 20 '15 at 13:36

1 Answers1

1

You cannot do that using the array_flip() function. Probably you look for something like that:

<?php
function array_flip_and_collect($input) {
  $output = [];
  foreach ($input as $key=>$val) {
    $output[$val][] = $key;
  }
  return $output;
}

$input = array(1,2,3,4,6,5,3,6);
print_r(array_flip_and_collect($input));

The output:

Array
(
    [1] => Array
        (
            [0] => 0
        )

    [2] => Array
        (
            [0] => 1
        )

    [3] => Array
        (
            [0] => 2
            [1] => 6
        )

    [4] => Array
        (
            [0] => 3
        )

    [6] => Array
        (
            [0] => 4
            [1] => 7
        )

    [5] => Array
        (
            [0] => 5
        )
)

Note that the output differs slightly from what you suggested in your question. That is by purpose because this appears more logical to me. If you really want that keys with only one element really are scalars and not arrays with one element, then you have to add an additional conversion step to the code.

arkascha
  • 41,620
  • 7
  • 58
  • 90