6

I have an array like this:

$data = array(
  "ID" => 1,
  "NAME" => "John Doe",
  "DATE" => date("d.m.Y H:i:s")
);

I want to create new variables with the name of the key and the value of the key like this:

$id = 1; 
$name = "John Doe";
$date = "17.11.2016 00:00:00";

I would like to do this with in for each loop, my current code looks like this:

foreach ($data as $key => $value) {

    $key = $data[$key];

}
8
  • 2
    Either look at extract() or for your foreach loop at variable variables. Commented Nov 17, 2016 at 21:06
  • What is your overall plan to use the variables for? Do you just want to put the values into an array and use them later? Commented Nov 17, 2016 at 21:07
  • 2
    Just put the array into the query. Commented Nov 17, 2016 at 21:12
  • 2
    Don't do it, just use the array. Commented Nov 17, 2016 at 21:29
  • 1
    Possible duplicate of Create new variables from array keys in PHP Commented Nov 17, 2016 at 22:57

2 Answers 2

10

PHP supports variable variables, although this is poor design you can just do:

foreach ($data as $key => $value) {

    $$key = $data[$key];

}
Sign up to request clarification or add additional context in comments.

Comments

6

Or you can use function extract for it.

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.