Page 1 of 1
Trying to use variable contents in the name for a variable.
Posted: Tue Feb 06, 2007 4:36 am
by impulse()
I have some DB retrieve code like this:
Code: Select all
while ($res = mysql_fetch_array($query)) {
if (!empty($res['G1'])) {
$G1['C'] = stripslashes($res['G1']);
$G1['N'] = stripslashes($res['G1Name']);
$G1 = 1;
}
if (!empty($res['G2'])) {
$G2['C'] = stripslashes($res['G2']);
$G2['N'] = stripslashes($res['G2Name']);
$G2 = 1;
And that goes to G10. I've created a loop like the following which isn't giving the desired results.
Code: Select all
for ($i = 1; $i < 11; $i++) {
echo $G$$i['C'];
echo $G$$i['N'];
}
I've read through the variable variables section on PHP.net but it doesn't seem to explain combining preset variable names with dynamic variables names.
Is there another way possible to do this?
Regards,
Posted: Tue Feb 06, 2007 5:06 am
by Kieran Huggins
I would just use a multidimensional array: $g['10']['c'] and $g['10']['n'] and $g['4']['c']....
also, by setting $Gx = 1 in your example, you're writing over the array you just created... not sure if that's intended.
Posted: Tue Feb 06, 2007 5:06 am
by Ollie Saunders
Code: Select all
$G1['C'] = stripslashes($res['G1']);
$G1['N'] = stripslashes($res['G1Name']);
$G1 = 1;
If you are just setting $G1 to 1 what was the point in the previous two operations.
I've read through the variable variables section on PHP.net but it doesn't seem to explain combining preset variable names with dynamic variables names.
I'm not entirely sure what you are trying to do there but something like this might help you:
Code: Select all
$foo1bar = 10;
$first = 'foo';
$num = 1;
echo ${$first . $num . 'bar'}; // outputs 10
Edit: Look everybody Kieran's back!
Posted: Tue Feb 06, 2007 5:24 am
by impulse()
Kieran Huggins wrote:I would just use a multidimensional array: $g['10']['c'] and $g['10']['n'] and $g['4']['c']....
also, by setting $Gx = 1 in your example, you're writing over the array you just created... not sure if that's intended.
I've taken this approach and it seems to work honky dory.
I was trying to use a preset variable name ($G) and then add a dynamic part onto the end of that preset variable. So if in a loop $i was 4 then I wanted to access the variable $G4 and if $i was 9 then to access variable $G9. It doesn't seem possible to do though and I'm not sure why I didn't use a multi-dimensional to start with. Could be because I've had a glass of orange juice instead of a strong coffee this morning.
Posted: Tue Feb 06, 2007 7:31 am
by Jenk
Variable variables, as ole pointed out, make it very much possible.
Code: Select all
for ($i = 0; isset(${'G' . $i}); $i++)
{
echo ${'G' . $i} . "\n";
}