Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array - Turning Array values into Keys

Tags:

arrays

php

key

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

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

INTO

$out = array(
    'red' => NULL,
    'green' => NULL,
    'blue' => NULL
);
like image 413
Alex V Avatar asked May 17 '12 18:05

Alex V


People also ask

How get key from value in array in PHP?

If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).

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

How do you create a key value pair from an array?

To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


1 Answers

Use PHP's array_flip function.


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);
like image 189
Travesty3 Avatar answered Oct 04 '22 04:10

Travesty3