0

I was wondering whether something like this is possible:

$var1 = 1; $var2 = 2;
function varsToArray($param1, $param2...);

and it returns array like this

array([var1] => 1, [var2] => 2).

Simply saying, I'd like arrays keys to be same as variable names. The problem is I don't know how to get variable name as string to put it as key(if possible of course...).

5
  • Well, since that's not valid PHP syntax it's obviously not possible to ascertain what you mean by it. Describe your goal. Commented Sep 19, 2011 at 15:29
  • 1
    possible duplicate of Create array names based on variable value ... please use the search before you ask a question. Commented Sep 19, 2011 at 15:30
  • @Felix Kling, nah, no exactly the same problem it seems Commented Sep 19, 2011 at 15:48
  • Then you did not describe your problem properly... the accepted answer puts the parameter names in the array, not the variable names, and I wonder why one would use reflection in this case. Commented Sep 19, 2011 at 15:49
  • Nope, I meant varaibles. Noticed after a while that Yoshi's solutions puts parameters names as keys, not varaibles names. Sry, my fault. The example i gave is bad, I'll change it Commented Sep 19, 2011 at 16:08

2 Answers 2

3

You want to use the compact function methinks.

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

2 Comments

compact works when you pass variables names as strings so compact("var1", "var2"); I wish to pass just as compact($var1, $var2). In this case @Yoshi's solution works fine:D
@f1ames: It works because the function's parameters are called $var1 and $var2. If you call foo($bar, $baz), the output will still contain var1, var2. I think passing the variable names as string is the only useful solution.
0

The built-in PHP function compact() does this.

BTW: I'm going to go ahead and assume that instead of:

function $varsToArray($var1, $var2...);

you actually meant:

function varsToArray($var1, $var2...);

Notice the dollar sign has been removed.

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.