Entry
Is it possible to cycle through a series of variables called Xpos1, Xpos2...
Is there a way to reference a variable combined of two variables, as in Perl? e.g.: $name$i?
Jul 10th, 2003 10:38
Philip Olson, Matt Jones,
Yes, but you should instead consider using an array. First, to
demonstrate how to accomplish what you're asking, we'll use "advanced
string syntax" by using braces, and creating variable variables:
<?php
$Xpos1 = 'green';
$Xpos2 = 'eggs';
$Xpos3 = 'are';
$Xpos4 = 'gross';
echo ${'Xpos' . 4}; // gross
for ($a = 1; $a <= 4; $a++) {
echo ${'Xpos' . $a};
}
?>
Now to accompish the same task, in a much more useful manner, consider
this example using an array:
<?php
$Xpos = array(1 => 'green', 2 => 'eggs', 3 => 'are', 4 => 'gross');
foreach ($Xpos as $key => $value) {
echo "$key : $value";
}
?>
Some related manual entries:
* http://www.php.net/manual/en/language.variables.variable.php
* http://www.php.net/manual/en/language.types.string.php