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?

d-_-b
  • 21,536
  • 40
  • 150
  • 256
  • Maybe you need a different approach. Can you explain a little more what you're ultimately trying to accomplish? – Joseph Jun 10 '14 at 00:52

3 Answers3

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

Daryl Gill
  • 5,464
  • 9
  • 36
  • 69
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

srain
  • 8,944
  • 6
  • 30
  • 42
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.

jeroen
  • 91,079
  • 21
  • 114
  • 132