Array copy values to keys in PHP

PhpArrays

Php Problem Overview


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

Php Solutions


Solution 1 - Php

$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.

Solution 2 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkusanagiView Question on Stackoverflow
Solution 1 - PhpKingCrunchView Answer on Stackoverflow
Solution 2 - Phpsebke CCUView Answer on Stackoverflow