sdfor
sdfor

Reputation: 6458

How to explode a string into an array with the string as Keys and the value true

I have:

$string = "option1,option2,option8";

I would like an array such as

$options = array ("option1" => true, "option2" => true, "option8" => true);

I can do:

$array = explode(",", $string);
$options = array();
foreach ($array as $k => $v) {
   $options[$v] = true;
}

I am wondering how to do it elegantly.

Upvotes: 0

Views: 63

Answers (2)

WizKid
WizKid

Reputation: 4908

By using array_fill_keys

$options = array_fill_keys(explode(',', $string), true);

Upvotes: 2

potashin
potashin

Reputation: 44601

You can use array_fill_keys() function :

$string = "option1,option2,option8";
$options = array_fill_keys(explode(',',$string), true);

Example

Upvotes: 2

Related Questions