Hướng dẫn dùng interchange keys trong PHP

I have an array like

$a = array['1'=>'one','2'=>'two','3'=>'three'];

I want to interchange key and value with each other using only for loop, and i want desired output like

$a = array['one'=>1,'two'=>2,'three'=>3]; 

asked Oct 17, 2015 at 18:00

Use array_flip:

$a = array['one'=>1,'two'=>2,'three'=>3];
$a_flipped = array_flip[$a];

If you insist on using a loop, then create a new empty array, iterate through the given array and fill the new array using values as keys, i.e.:

$a = array['one'=>1,'two'=>2,'three'=>3];
$a_flipped = array[];
foreach [$a as $key => $value] {
    $a_flipped[$value] = $key;
}

answered Oct 17, 2015 at 18:02

Alex ShesterovAlex Shesterov

24.5k12 gold badges75 silver badges96 bronze badges

2

using a foreach loop:

 

answered Oct 17, 2015 at 18:17

2

Not the answer you're looking for? Browse other questions tagged php arrays for-loop or ask your own question.

Chủ Đề