views:

73

answers:

4

Hi,

$str='input_arr["username"]';

$input_arr=array();

$$str='abcd';

print_r($input_arr);

When I run the above code it only prints Array().

I expected it to print Array([username]=>'abcd')

What am I doing wrong?

This is in php 4 by the way.

Thanks a lot.

Edit:What am I trying to do?

$input_arr is supposed to be a static variable to hold validated user input.However, I only recently realised that php4.3 doesnt support self::$input_arr so I had to edit my script to bar($input_arr['name'],$value); so that I can save the value to a static variable in bar();since $input_arr['name'] does not exists in the current scope, I had to make it a string.

A: 

Hi,

yeah you are wrong.

$$str is the address of the real location of the variable in memory, it's only use when you want to do reference passing parameters.

print_r($input_arr) print an empty array because 4input_arr it's not declare, so will be declare by php with an empty content.

look about other ways

Leonzo Constantini
How exactly are references and variable variables related?
janmoesen
+1  A: 
janmoesen
@Mystery person: care to explain the downvote? I think this is the safest approach (keeping in mind that variable variables still smell like bad code design) and I made it clear that eval is evil. Are you objecting to the use of the tokenizer instead of eval, perhaps?
janmoesen
someone going nuts on the downvotes :p code looked clean to me, upvoted.
danp
A: 

It's still difficult to tell what you're trying to do, but it sounds like you want $str to determine where inside $input_arr a piece of data lives. If so, you should store only the array key(s) in $str, not a string representation of the code.

In your last example, it's as simple as setting $str = 'name' and then using $input_arr[$str] to access $input['name']. In the first case, you could use an array $keys = array(3,5) instead of $str, and then $input_arr[$keys[0]][$keys[1]] would be equivalent to $input_arr[3][5].

grossvogel
A: 

It could work with 2 variables if you really want this. Even better if you use a reference to the array instead of a variable variable.

$input_arr = Array();

function somefunction($array, $key)
{
    ${$array}[$key] = 'abcd';
}

function betterfunction(&$array, $key)
{
    $array[$key] = 'abcd';
}

somefunction('input_arr', 'username');
betterfunction($input_arr, 'username');
VirtualBlackFox