1

Lets say I have the following array:

$array_1 = [         
         'Green' => 'Tea',
         'Apple' => 'Juice',
         'Black' => 'Coffee',
      ];

How do I flip the key => value of only one part of the array to something like this:

   $array_2 = [         
         'Tea' => 'Green',
         'Apple' => 'Juice',
         'Black' => 'Coffee',
      ];

I know there is a function array_flip() but it flips the whole array, how do I go about flipping only a selected key value pair in the array?

3
  • 3
    What is the logic for which keys should be flipped? Commented Sep 26, 2022 at 20:43
  • @Barmar Currently no logic - I'm simply asking out of curiosity as I'm new to PHP and noticed array_flip() only does the whole array Commented Sep 26, 2022 at 20:48
  • There's nothing built-in. Just add the new element and delete the old one. Commented Sep 26, 2022 at 20:53

2 Answers 2

2

The following code just flips all elements of the array. It just does the same thing as array_flip:

$array_2 = array();
foreach ($array_1 as $key => $value) {
    $array_2[$value] = $key;
}

Now if you want to flip an element in the array, you need to code like the following. Suppose you want to flip just 'Apple' in your element. You need to wait for that element in a foreach loop, and when you catch it, flip it. Try the following just to flip the 'Apple' key.

    $array_2 = array();
    foreach ($array_1 as $key => $value) {
        if ($key === 'Apple') {
            $array_2[$value] = $key;
        } else {
            $array_2[$key] = $value;
    
        }
    }

Try this online!

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

Comments

1

There's nothing that does this. Just assign the flipped key and delete the old key.

$key_to_flip = 'Green';
$array_2 = $array_1;
unset($array_2[$key_to_flip]);
$array_2[$array_1[$key_to_flip]] = $key_to_flip;

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.