2

I have a multidimensional array and I want to create new variables based on the keys.

I have written this code, but it returns NULL:

$a = array("test" => array("a", "b", "c"));
foreach($a as $key => $value){
    if(is_array($value)){
        $i = 0;
        foreach($value as $v){
            $i++;
            $$key[$i] = $v;
        }
    }
}
var_dump($test);
?>

Where is the problem?

0

3 Answers 3

7

Make that:

${$key}[$i] = $v;
  • $$key[$i] means "the variable whose name is $key[$i]".
  • ${$key}[$i] means "position $i from the variable whose name is $key".

Also, it would be nice if you could initialize that $test array, so you won't get notices. Add the following before the second foreach:

$$key = array();
Sign up to request clarification or add additional context in comments.

Comments

3

+1 to @Radu's answer, but you should also think about if these solutions would work for you:

$a = array("test" => array("a", "b", "c"));
foreach($a as $key => $value){
    if(is_array($value)){
      $$key = array_values($value);
    }
}
var_dump($test);

Or:

$a = array("test" => array("a", "b", "c"));
extract($a);
var_dump($test);

See: array_values(), extract().

Comments

1

$$key[$i] tries to get the variable whose name matches the value of $key[$i]. You could get a reference to $$key first, and then add an item to that reference:

$a = array("test" => array("a", "b", "c"));
foreach($a as $key => $value){
    if(is_array($value)){
        $i = 0;
        foreach($value as $v){
            $i++;
            $x = & $$key;
            $x[$i] = $v;
        }
    }
}
var_dump($test);
?>

[edit]

But I see, I'm somewhat slow in testing and writing an answer, since another good answer has been posted minutes ago. Still keeping this, since it uses a different and not much more complex approach.

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.