2

I have Multidimensional array with key value pair so I want to flip i.e key gets to value place and values get to key place but I am getting error

My Php code is:

echo '<pre>',print_r($res),'</pre>';

output when print_r($res):

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

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

    [2] => Array
        (
            [userid] => 3
        )

)

getting error in output when want to flip this array:

array_flip(): Can only flip STRING and INTEGER values!

How to solve this?

5
  • 3
    What result are you trying to achieve? Commented Feb 13, 2019 at 6:10
  • @Nick I want to flip means array value should come to its key place and key get changed to value position Commented Feb 13, 2019 at 6:13
  • Can you show in your question what you expect as output, it may be quite simple but as already pointed out it's not clear at the moment. Commented Feb 13, 2019 at 6:51
  • array_flip() does not flip array as values. array_flip() can only flip string and integer values. Commented Feb 13, 2019 at 6:53
  • Is this an XY Problem? I can't see any benefit in flipping this deep data. Commented Aug 28, 2021 at 22:26

3 Answers 3

6

You are trying to flip a multidimensional array where each value is an array, but according to the docs of array_flip:

Note that the values of array need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be included in the result.

You could use array_map to use array_flip on each entry:

$a = [
    ["userid" => 1],
    ["userid" => 2],
    ["userid" => 3],
];

$a = array_map("array_flip", $a);

print_r($a);

Result

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

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

    [2] => Array
        (
            [3] => userid
        )

)

See a php demo

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

1 Comment

thanks for your valuable time which have solved my problem.
1

array_flip() does not flip array as values. array_flip() can only flip string and integer values.

You can try this:

 $arr = [
   [ 'userid' => 1 ],
   [ 'userid' => 2 ],
   [ 'userid' => 3 ]
];
foreach($arr as $a){
    $flipped[] = array_flip($a);
}
print_r($flipped);

Comments

0

You can try the following way

$arr = [
   [ 'userid' => 1, ],
   [ 'userid' => 2, ],
   [ 'userid' => 3, ]
];
array_walk($arr, function(&$val) { $val = array_flip($val); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.