faqts : Computers : Programming : Languages : PHP : kms : General : Variables

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 3 people (100%) answered Yes
Recently 3 of 3 people (100%) answered Yes

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