Reputation: 719
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
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
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