2

I often see or have to convert a bunch of variables into an array like this:

$array = array("description"=>$description, "title"=>$title, "page"=>$page, "author"=>$author);

Basically, all array keys match the name of the variable that is being passed in. Is there a way to reference a variable name so that it can be passed into the array like so:

$array[varName($description)] = $description;
StackOverflowed
  • 5,854
  • 9
  • 55
  • 119

1 Answers1

11

You could use compact [docs]:

$array = compact('description', 'title', 'page', 'author');

Each argument is a variable name and it will create an array with the key being the name and the value being the value of the variable with that name.

It's the other way round than your approach though.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143