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;
4
  • 4
    Seems like this is the wrong approach. If the values have already been saved to variables, that seems to imply you had the opportunity to store them as array keys in the first place?? Commented Mar 17, 2013 at 13:22
  • @mavili How can variable variable be helpful here? Commented Mar 17, 2013 at 13:31
  • it doesn't, does it? I shall remove that then ;) Commented Mar 17, 2013 at 13:32
  • not a dupe, as indicated by the answer by Felix King. Commented Mar 17, 2013 at 13:37

1 Answer 1

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.

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

7 Comments

+1 Never heard of compact before
+1 @MathieuImbert Me neither - but can't help thinking it seems a bit "hackish"?
Never heard of compact, +1!
@Emissary, if you think this is hackish, I'd avoid most of PHP! :) (not disagreeing with your assessment however).
@StackOverflowed I can't fault you there - if I ever catch one of my subordinates using that I'll be telling them where they can goto...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.