Jump to content

Dynamic Var Names


Kryptix

Recommended Posts

Can you make a var name by doing something like this:

 

<?php
for ($i = 0; $i < 5; $i++) {
	$var . $i = "Var " . $i . " set...<br />";
}

echo $var1;
echo $var2;
echo $var3;
echo $var4;
?>

 

Is it possible at all?

 

I really need to do it, make a variable name whatever the loop count is.

Link to comment
https://forums.phpfreaks.com/topic/191436-dynamic-var-names/
Share on other sites

There is probably another way than this but its the only way I know.

 

<?php
$array=array();
for ($i = 0; $i < 5; $i++)
{$array['var'.$i] = "Var " . $i . " set...<br />";

}
extract($array);

echo "var1::$var1<br>";
echo "var2::$var2<br>";
echo "var3::$var3<br>";
echo "var4::$var4<br>";

?>

 

 

HTH

Teamtomic

Link to comment
https://forums.phpfreaks.com/topic/191436-dynamic-var-names/#findComment-1009216
Share on other sites

$GLOBALS[var1] is the same as $var1.

 

I would think that to be only true of register_globals is turned on, which it should be turned off, as if it is not that can cause some security loop holes. As such, you should always define a variable before you use it blindly. This way you know what it should contain and not have to guess. As far as which way is better, imo I would prefer Jay's way as it tends to be less code.

 

Nothing against you team, just providing some more information on the matter.

Link to comment
https://forums.phpfreaks.com/topic/191436-dynamic-var-names/#findComment-1013298
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.