Ryan Jameson (USA) wrote:

Hi Folks,

I've been using "variable variables" for years with PHP.

I'm not really sure this is really good practice. Sure, php allows it but I think you should try to avoid them.

$var = "myVarName";
$$var = "Some Val";

echo $myVarName; //outputs "Some Val"

.... Today I am trying to assign an Associative Array value to a "variable
variable". For some reason it doesn't take. Does anyone know why?



$varName = "myVarName";
$$varName = $var;

echo $$varName['second']; //should output "frank" but doesn't. :-\
echo $var['second']; //should output "frank" works fine.

I'm not really sure what the problem is over here, but the obvious answer would be that PHP might not allow it's use on arrays.

The reason I want to do this is to speed up access to DATABASE query
results by use of the associative array. Since the results are keyed on
a specific column I'd like to load the very small recordset and then
access each row associatively on that column value. Currently I have to
requery the database every time, which is faster than loop/testing the
whole result set each time. I'd use a hashtable in Java but PHP ain't
Java. If ne1 has a better way I'm game.

Really, everyhing you describe can be done with normal arrays. Perhaps you should give a sample of the code so I could have a look and give ideas on how you could rewrite it.
The easiest way to rewrite your above example would be:

$var['first'] = 'bob';
$var['second'] = 'frank';

$myChangingVar =& $var;

echo $myChangingVar['second'];   //outputs frank;
$myChangingVar['second'] = 'Michael Jackson';

echo $var['second'] // outputs USA's #1 icon


Thanks for your help.
<>< Ryan

-- PHP Database Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to