PHP数组 - 将数组值转换为键

时间:2021-12-22 10:45:15

What is the MOST EFFICIENT way to have an array of values and turn it into an array of keys? I'd really like to avoid any foreach loop...

拥有一系列值并将其转换为键数组的最有效方法是什么?我真的想避免任何foreach循环......

$in = array(
    'red',
    'green',
    'blue'
);

INTO

INTO

$out = array(
    'red' => NULL,
    'green' => NULL,
    'blue' => NULL
);

1 个解决方案

#1


26  

Use PHP's array_flip function.

使用PHP的array_flip函数。


On second thought, if you want the values to be null, then you might want to use array_fill_keys:

$out = array_fill_keys($in, null);

#1


26  

Use PHP's array_flip function.

使用PHP的array_flip函数。


On second thought, if you want the values to be null, then you might want to use array_fill_keys:

$out = array_fill_keys($in, null);