nielsv
nielsv

Reputation: 6820

Replace keys with values (but don't flip)

I have an array like this:

["AF"]=> string(11) "Afghanistan" 
["002"]=> string(6) "Africa" 
["AL"]=> string(7) "Albania"
 ...

Now I would like to have an array like this:

["Afghanistan"]=> string(11) "Afghanistan" 
["Africa"]=> string(6) "Africa" 
["Albania"]=> string(7) "Albania"
 ...

Is this possible without looping through them? (Is there a php function for this?) When I searched Google I found arary_flip but that's switching the keys and values...

Upvotes: 1

Views: 69

Answers (3)

ɹɐqʞɐ zoɹǝɟ
ɹɐqʞɐ zoɹǝɟ

Reputation: 4370

I think array_combine() is what you need

$a = array_combine($a, $a);

Upvotes: 5

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

$names = array("AF"=>"Afghanistan" ,"002"=>"Africa" ,"AL"=>"Albania");
$names = array_combine($names, $names);
print_r($names);

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76636

Use array_combine():

$result = array_combine($array, $array);

Or for better readability:

$keys = $values = array_values($arr);
$result = array_combine($keys, $values);

Demo

Upvotes: 7

Related Questions