Splash Posted July 24, 2007 Share Posted July 24, 2007 Hello everyone. I'm working on a project at the moment and have hit a bit of a brick wall, and am hoping you guys can help me with it. Basicaly I'm trying to create a new variable by adding a string onto the end of the variable name. i.e. $Variable1 = 1; $Variable2."$Variable1" = "Value" $Variable1++; $Variable2."$Variable1" = "Value" Which would result in $Variable21 = "Value" $Variable22 = "Value" Does anyone know how this can be achieved? Thankyou Splash Quote Link to comment Share on other sites More sharing options...
btherl Posted July 24, 2007 Share Posted July 24, 2007 You can do this: $n = 1; $varname = 'Variable' . $n; $$n = 'Value'; print $Variable1; The "$$" is what allows it to work. The other option is using eval(), but there's no need for that in this case. Quote Link to comment Share on other sites More sharing options...
Splash Posted July 24, 2007 Author Share Posted July 24, 2007 Ah that looks good to me, I'll try it and let you know how I get on. Quote Link to comment Share on other sites More sharing options...
DeadEvil Posted July 24, 2007 Share Posted July 24, 2007 ..OR $ctr = 1; $variable = $Variable2.$ctr; $variable = "Value"; print $variable; $ctr = ++; $variable = $Variable2.$ctr; $variable = "Value"; print $variable; Quote Link to comment Share on other sites More sharing options...
btherl Posted July 24, 2007 Share Posted July 24, 2007 Sorry, I'm tripping.. I meant to say $$varname = 'Value'; Quote Link to comment Share on other sites More sharing options...
Splash Posted July 24, 2007 Author Share Posted July 24, 2007 Btherl you're a legend! Works a treat! Quote Link to comment Share on other sites More sharing options...
Barand Posted July 24, 2007 Share Posted July 24, 2007 Why not just use an array? <?php $var = array(); $var[] = 'first value'; $var[] = 'second value'; $var[] = 'third value'; echo $var[0]; // --> 'first value' echo '<pre>', print_r($var, true), '</pre>'; // --> // Array // ( // [0] => first value // [1] => second value // [2] => third value // ) ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.