reformed
reformed

Reputation: 4808

PHP Explode Populate Keys Not Values

Let's say you have a comma-delimited string:

$str = 'a,b,c';

Calling explode(',', $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)

Upvotes: 1

Views: 155

Answers (3)

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

You can simply use explode with foreach

$res = [];
foreach(explode(",", $str) as $key){
  $res[$key] = null;
}
print_r($res);

https://3v4l.org/KGlfA

Upvotes: 0

Nick
Nick

Reputation: 147216

You can use array_fill_keys 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
}

Demo on 3v4l.org

Upvotes: 3

Alberto
Alberto

Reputation: 12949

something like this:

$str = 'a,b,c';
$arr = [];
foreach ($explode(',', $str) as $key) {
    $arr[$key] = null;
}

not that pretty but it works

Upvotes: 0

Related Questions