3
$input = "hello|world|look|at|this";
$explode = explode("|", $input);
$array = array("Title" => "Hello!", "content" => $explode);

This will output:

array(2) {
  ["Title"]=>
  string(6) "Hello!"
  ["content"]=>
  array(5) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(5) "world"
    [2]=>
    string(4) "look"
    [3]=>
    string(2) "at"
    [4]=>
    string(4) "this"
  }
}

But I want them to be keys with a NULL as value as I add values in a later step.

Any idea how to get the explode() function to return as keys? Is there a function from available?

1
  • array_fill_keys() when you're creating the array in the first place Commented Jan 15, 2014 at 9:21

4 Answers 4

2

array_fill_keys can populate keys based on an array:

array_fill_keys ($explode, null);
Sign up to request clarification or add additional context in comments.

Comments

0

Use a foreach loop on the explode to add them:

foreach($explode as $key) {
    $array["content"][$key] = "NULL";
}

Comments

0

how about array_flip($explode)? That should give you this

array(2) {
 ["Title"]=>
 string(6) "Hello!"
   ["content"]=>
    array(5) {
      [hello]=> 1

No nullvalues but atleast you got the keys right

1 Comment

Values wouldn't be null. However you could do something after such as foreach($new_explode as &$val) { $val = null; } after.
0
$input = "hello|world|look|at|this";
$explode = explode('|', $input);
$nulls = array();
foreach($explode as $x){ $nulls[] = null; };
$array = array("Title" => "Hello!", "content" => array_combine($explode, $nulls));

Comments

Your Answer

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