Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 557
T K Avatar asked Dec 18 '22 11:12

T K


1 Answers

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

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

    $$key = $data[$key];

}
like image 156
TravisO Avatar answered Dec 21 '22 00:12

TravisO