Variables Variable Question – PHP

  php

Q(Question):

As you might have guessed from some of my questions today, I am trying to automate a lot of my pages with for loops. However I have become stuck, yet again!

I want to call several different variables depending on which cycle the for loop is in, so I have the following:
[php]$var_data_name = "var_data[‘cost_".$i."’]";
echo($var_data_name."<br />"); // prints: var_data[‘cost_1’]
echo($$var_data_name."<br />"); // prints: {nothing}
echo($var_data[‘cost_1’]."<br />"); // prints: 1000 (value of cost_1)[/php]
However, if I don’t use the array it works:
[php]$bar_cost_1=var_data[‘cost_1’];
$var_data_name = "bar_cost_".$i;
echo($var_data_name."<br />"); // prints: bar_cost_1
echo($$var_data_name."<br />"); // prints: 1000
echo($var_data[‘cost_1’]."<br />"); // prints: 1000 (value of cost_1)[/php]

So I know the problem is using an array in the vars var, but does anyone know how to get around it? I am happy to do it this way, but I was wondering if there is simple syntax which needed specifically for arrays or something?

A(Answer):

Actually, I have found a better way to do it, but I am interested to find it out anyway for future reference if anyone knows the answer!

A(Answer):

See also chapter Variables variable in the PHP documentation. This handles the ambiguity of using indexes in var-vars. When I need to use it I use the eval() function. Like this[php]<?php
$var_data[‘cost_1’]=1000;
$i=1;
$var_data_name = "var_data[‘cost_".$i."’]";
echo("1. ".$var_data_name."<br />"); // prints: 1. var_data[‘cost_1’]
echo("2. ".$$var_data_name."<br />"); // prints: 2. {nothing}
echo "3. ".eval("return \$$var_data_name;")."<br>"; // prints 3. 1000
echo("4. ".$var_data[‘cost_1’]."<br />"); // prints: 4. 1000 (value of cost_1)
?>[/php]Ronald

A(Answer):

Try enclosing the sub-variable in squigly brackets:

echo($$var_data_name."<br />"); // prints: {nothing}

becomes

[PHP]echo(${$var_data_name}."<br />"); [/PHP]

A(Answer):

Great solutions, I will give that a go as soon as I get home.

A(Answer):

Ron,
echo (eval("return \$$race_data_name;")."<br />"); works perfectly! I will change my script to this for now.

aktar,
Your’s in the one I have been trying to do for ages, but I can’t get it to work? Have you tried your suggestion? If I can get it to work with the same logic as yours then that will be my solution.

A(Answer):

aktar‘s solution does not work for me either. And I am not quite sure why it should work, reading the variables-variable chapter in the PHP documentation in the link I previously posted.

Ronald

LEAVE A COMMENT