开发者

Array copy values to keys in PHP [duplicate]

This questio开发者_如何学JAVAn already has answers here: Create an assoc array with equal keys and values from a regular array (3 answers) Closed 6 years ago.

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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜