5

I'm not sure how to ask this question, but here goes:

$id = 1;
$age = 2;    
$sort = "id"; // or "age";

$arr = array($$sort => 'string'); // so that it becomes 1 => 'string' 
             ^ what goes here?    //      instead of 'id' => string'

Is this something that the & character is used for, "variable variables"?

or maybe eval?

1
  • Maybe you need a different approach. Can you explain a little more what you're ultimately trying to accomplish? Commented Jun 10, 2014 at 0:52

3 Answers 3

5

on topic to your question. With the logic of PHP, the best way I can see this being done is to assign your variable variables outside the array definition:

$id = 1;
$age = 2;    
$sort = "id"; // or "age";
    $Key = $$sort;
$arr = array($Key => 'string');

print_r($arr);

Which outputs:

Array ( [1] => string )

Though, personally. I'd suggest avoiding this method. It would be best to define your keys explicitly, to assist with backtracing/debugging code. Last thing you want to do, is to be looking through a maze of variable-variables. Especially, if they are created on the fly


Tinkering. I've got this;

$arr[$$sort] = "Value";

print_r($arr);

I've looked into the method to creating a function. I do not see a viable method to do this sucessfully. With the information i've provided (defining out of array definition), hopefully this will steer you in the right direction

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

Comments

2

If you use:

$arr = array($sort => 'string');

will be id => string, but if you use

$arr = array($$sort => 'string');

$sort will be id and $$sort will be $id, and it's value is 1, so: 1 => string

Comments

1

I would not use variable variables for that, but an array that connects the correct keys to the values you need:

$sorts = array('id' => 1, 'age' => 2);
$sort = 'id';

$arr = array($sorts[$sort] => 'string');

An example.

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.