PHP variable variable head spin

Status
Not open for further replies.

clm100

Ars Legatus Legionis
13,874
Subscriptor
I'm writing a page where there are several ways to sort data and I need to put anchors in (see my other lovely thread about that). The problem is that depending on how the data is being sorted different anchors need to be inserted in different places. I want to just be able to declare how I want a function (substr) to operate later on and then call it.

so up in my if statements have something like
Code:
$choice = '$row["field"], 0, 1';
but the problem is I don't want to refer to $row["field"] NOW, I want to refer to it later when the variable is called. I think I can do it somehow with variable variables, but the documentation doesn't pierce my sleep deprived and tired brain. Thanks a million and a half.

I know this didn't make any sense, but can we just pretend?
 

clm100

Ars Legatus Legionis
13,874
Subscriptor
All right, I've thought of another way to explain it, kinda.

You know how in linux you can feed the output of one command into another with grep cheese `cat /home/junk` or whatever? I want to take the output of a variable and treat it as if it were plain text I just typed in.

So at the top of the page we have:
Code:
if(option1) {
    $key = '$option1';
} else {
    $key = '$option2';
}
$letter = substr($key, 0, 1);

The reason is that I want to use different different variables for the substr command depending on which option was chosen, but I don't want $key to be searched for, I want the contents of $key to be treated as another variable to be looked up when $key is called (not assigned).

Was that any better?
 

CanSpice

Ars Tribunus Angusticlavius
7,147
Makes perfect sense. :) What you want to do is have a string that has variable names in it, then later evaluate that string.

If it helps any, there's a PHP function called "eval", which will evaluate any string as PHP. You should be able to escape out the $'s from your strings and then pass them to eval.

I can't come close to explaining how it works (since I haven't done it with PHP), but there's a seemingly excellent batch of comments at the PHP eval documentation. Hopefully that'll spur some inspiration for you.
 

clm100

Ars Legatus Legionis
13,874
Subscriptor
Hrm, well it looks like what I want, but it doesn't work.
Here is the relevant code, and the output. Key contains exactly the string I want it to later contain. And yes $row["lname"] exists
Code:
$key = '$row["lname"]';
echo $key;
eval ("\$key = \"$key\";");
echo "$key

";
$row["lname"]
Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in /pinky/httpd/bnc/equip/listusers.php(31) : eval()'d code on line 1
$row["lname"]

Ah, so I fixed it. I'd already used the variable $row["lname"] aparently, so I just declared $lname = $row["lname"] and used it in both places. :mad: :rolleyes:
 
Status
Not open for further replies.