T K T K - 21 days ago 5
PHP Question

Array key = variable name

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];

}

Answer

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

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

    $$key = $data[$key];

}