Jump to content

Archived

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

endy

How to increment a variable?

Recommended Posts

Hello,
I am trying to use a "while" loop to create a bunch of variables, however it doesnt seem to be working. Is there a way to concatenate a variable name with another variable? Here is what I am trying to do:
[code]$i=0
while($i<5) {
$my_var.$i="something";
$i++;
}[/code]

So I just want to get a series of variables ($my_var1, $my_var2, $my_var3,...) that are all equal to "something";

Is it possable?
THanks!

Share this post


Link to post
Share on other sites
Yes, you want to use variable_variables.
[code]<?php
for ($i=0;$i<5;$i++) {
${'my_var'.$i}="something";
}?>[/code]
but it would be much easier to use an array here:
[code]<?php
$myvar = array();
for($i=0;$i<5;$i++)
    $myvar[] = "somthing $i";
echo '<pre>'.print_r($myvar,true).'</pre>';
?>[/code]

Ken

Share this post


Link to post
Share on other sites

×

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.