193

I have this array:

$a = array('b', 'c', 'd');

Is there a simple method to convert the array to the following?

$a = array('b' => 'b', 'c' => 'c', 'd' => 'd');
0

2 Answers 2

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

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one'];

Note the duplicated one element.

1
  • array_combine is a bit slow compared to in_array. array_combine vs in_array vs isset performance test: onlinephp.io/c/12411
    – csandreas1
    Jan 7 at 7:04
-10

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So I solved it like this:

foreach($array as $key => $val) {
    $new_array[$val]=$val;
}
1
  • 10
    The above is incorrect - your quote comes from the documentation for array_merge and not array_combine; I even tested it with array_combine and the latter value, even in numeric key arrays always overwrites the former one.
    – Brett
    Apr 2, 2017 at 20:13

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