Page 1 of 1
Parsing $variable value
Posted: Tue Sep 09, 2008 3:46 am
by Tokci
I've a problem which I'm not able to figure out. I'm fetching some values from the db, which store some variable name.
For example, results from the db will be :
Code: Select all
array('parameter_name'=>'id','parameter_value' => '$id')
In the page I'm retrieving the result there is already a variable named $id (with a some value, say 'Test').
Now my problem is that I need to echo the value of result['parameter_value'] and it should print 'Test', but currently its echoing $id.
I've used:
Code: Select all
echo result['parameter_value'];
echo "result['parameter_value']";
Kindly let me know if this is at all possible or is there a workaround.
Looking forward for some guidance...thnx.
Re: Parsing $variable value
Posted: Tue Sep 09, 2008 3:55 am
by onion2k
You need to use a reference, also known as a "variable variable".
Instead of storing $id in the database just store the name of the variable, eg id. Then use $$result['parameter_value'] to access it. Note the two $ signs. PHP parses the first to get 'id' then parses the second to get the value of ${'id'}.
They're very powerful. They're also a very easy way to write code that's virtually impossible to debug. So be careful.
Re: Parsing $variable value
Posted: Tue Sep 09, 2008 7:29 am
by Tokci
onion2k wrote:You need to use a reference, also known as a "variable variable".
Instead of storing $id in the database just store the name of the variable, eg id. Then use $$result['parameter_value'] to access it. Note the two $ signs. PHP parses the first to get 'id' then parses the second to get the value of ${'id'}.
They're very powerful. They're also a very easy way to write code that's virtually impossible to debug. So be careful.
Hey ...just figured it out few minutes back...I'm doing the exact same thing you mentioned....so I guess I'm on the right track.
Thnx a lot for your input, I really appreciate it.
Re: Parsing $variable value
Posted: Tue Sep 09, 2008 7:48 am
by marcth
There's an error in your code:
Code: Select all
array('parameter_name' => 'id','parameter_value' => $id)
If you wrap the $id variable in single quotes it becomes the string '$id' and not the value of $id
Re: Parsing $variable value
Posted: Tue Sep 09, 2008 8:23 am
by onion2k
marcth wrote:There's an error in your code:
Code: Select all
array('parameter_name' => 'id','parameter_value' => $id)
If you wrap the $id variable in single quotes it becomes the string '$id' and not the value of $id
If you'd read the post properly you'd know that's what he wanted.