PDA

View Full Version : Help! Using a variable's value as part of another variable name


JakeG
Sat 18th Aug '01, 6:16am
I'm tearing my hair out over this and if someone doesn't help me out soon I'll be left bald before I'm 20!

I've got a variable defined like $kind = "agent"; and would like to use the value of this variable (agent for example) as part of another variable's name, like this:

I want a variable called $agent_list. How can I do this without having to type 'agent' again, and instead calling the value of the $kind variable? I can't find the correct syntax in all the PHP books I've got and don't really know where to look. The closest I can find is $$kind to make a variable called '$agent' but I want the variable to be called $agent_list because I want to set a few variables with the word 'agent' in them.

Here's the full code for my function at the moment - wherever it says $kind that's where I want the value of $kind inserted, often to make a new variable name:

function area_match($kind) {
global $where_string, $result;
do_query("SELECT " . $kind . "id FROM " . $kind . "_area WHERE $where_string");
while ($data = mysql_fetch_array($result)) {
$$kind_list[] = $data['${$kind}id'];
}
$kind_list = array_unique($kind_list);

$where_string = $kind . "id = '";
$where_string .= join("' OR " . $kind . "id = '", $kind_list);
$where_string .= "'";
if ($where_string == $kind . "id ='") $where_string = "areaid = '999999'";
}

Your help is much appreciated!

Mark Hensler
Sat 18th Aug '01, 1:59pm
$kind = "agent";
eval("\$" . $kind . "_list=\"blah\";");
echo $agent_list;
// blah

//OR

$kind = "gent";
${$kind."_list"}="blah";
echo ${$kind."_list"};
// blah

JakeG
Sun 19th Aug '01, 2:04pm
Thanks Max Albert,

And to extend this question, one other thing which I never seem to be able to do. I want to declare certain variables to be global, where those variables are part of an array. For example:

$global_var = array("something", "thingy", "variable3");

where "something" refers to the variable $something etc.

I want all of these variables in the array to be defined as global, like:

global $something, $thingy, $variable3

I think that should make sense. How do I do this?

Mark Hensler
Mon 20th Aug '01, 1:50am
try this:

$global_var = array("something", "thingy", "variable3");
foreach ($global_var as $tmp) {
global ${$tmp};
}