arrays - PHP Explode Populate Keys Not Values

Let's say you have a comma-delimited string:
$str = 'a,b,c';
Callingexplode(',', $str);
will return the following:
array('a', 'b', 'c')
Is there a way to explode such that the resulting array's keys, and not values, are populated? Something like this:
array('a' => null, 'b' => null, 'c' => null)
Answer
Solution:
You can use to use the output of
explode
as keys to a new array with a given value:
$str = 'a,b,c';
$out = array_fill_keys(explode(',', $str), null);
var_dump($out);
Output:
array(3) {
["a"]=>
NULL
["b"]=>
NULL
["c"]=>
NULL
}
Answer
Solution:
something like this:
$str = 'a,b,c';
$arr = [];
foreach ($explode(',', $str) as $key) {
$arr[$key] = null;
}
not that pretty but it works
Answer
Solution:
You can simply use explode withforeach
$res = [];
foreach(explode(",", $str) as $key){
$res[$key] = null;
}
print_r($res);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xml parsing error: no root element found
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.