user3056158
user3056158

Reputation: 719

How to interchange array keys and values using for loop?

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); 

Upvotes: 0

Views: 212

Answers (2)

user5304601
user5304601

Reputation:

using a foreach loop:

 <?php 

    $a = array('1'=>'one','2'=>'two','3'=>'three');

    $tmp = array();

    foreach($a as $key=>$value){
        $tmp[$value] = $key;

    }

?>

Upvotes: 1

Alex Shesterov
Alex Shesterov

Reputation: 27525

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;
}

Upvotes: 5

Related Questions