19

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

1 Answer 1

45

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.