0

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

2 Answers 2

5

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

i want do this with for loop not with array function.
@user3056158, although I can't see any reasons of using a loop rather than a built-in function, I edited the answer and included the loop solution.
1

using a foreach loop:

 <?php 

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

    $tmp = array();

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

    }

?>

2 Comments

could u make it with for loop?
$a = array('1'=>'one','2'=>'two','3'=>'three'); $tmp = array(); for($i=1; $i<=count($a); $i++){ $tmp[array_search($a[$i], $a)] = $a[$i]; }

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.