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;
}
Simply use this logic
where $arr1 is the array that has to be converted to associative array. This can be achieved by json_encode and the json_decode the same
array_flip()
is exactly doing that:But apart from that, there is only one type of array in PHP. Even numerical ("simple", as you call it) arrays are associative.
Your code is the exact equivalent of:
array_flip()
, while it may work for your purpose, it's not the same.PHP ref:
array_fill_keys()
,array_flip()
If anyone is still wondering how to do this, there is an easier solution for this by using the array_combine function.