Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a simple array to an associative array?

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; } 
like image 754
user773755 Avatar asked May 27 '11 14:05

user773755


People also ask

How do you convert an array into associative array?

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

What syntax is used to create an associative array?

Here array() function is used to create associative array.

How do you find an associative array?

If count(filtered_array) == count(original_array), then it is an assoc array. If count(filtered_array) == 0, then it is an indexed array.


2 Answers

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()

like image 178
Alix Axel Avatar answered Sep 27 '22 20:09

Alix Axel


array_flip() is exactly doing that:

array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.

Note that the values of trans need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be flipped.

If a value has several occurrences, the latest key will be used as its values, and all others will be lost.


But apart from that, there is only one type of array in PHP. Even numerical ("simple", as you call it) arrays are associative.

like image 31
Felix Kling Avatar answered Sep 27 '22 20:09

Felix Kling