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?

2
  • 1
    stackoverflow.com/a/30795697/2899618 Commented Aug 20, 2015 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? Commented Aug 20, 2015 at 13:36

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.