Home > OS >  PHP - Is it possible to flip only a specific part of a key value array?
PHP - Is it possible to flip only a specific part of a key value array?

Time:09-27

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?

CodePudding user response:

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;

CodePudding user response:

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!

  • Related