How to convert a simple array to an associative array?

user773755 picture user773755 · May 27, 2011 · Viewed 57.7k times · Source

What is the fastest way to convert a simple array to an associative array in PHP so that values can be checked in the isset($array[$value])?

I.e. fastest way to do the following conversion:

$array = array(1, 2, 3, 4, 5);
$assoc = array();

foreach ($array as $i => $value) {
        $assoc[$value] = 1;
}

Answer

Alix Axel picture Alix Axel · May 27, 2011

Your code is the exact equivalent of:

$assoc = array_fill_keys(array(1, 2, 3, 4, 5), 1); // or
$assoc = array_fill_keys(range(1, 5), 1);

array_flip(), while it may work for your purpose, it's not the same.

PHP ref: array_fill_keys(), array_flip()