Jump to content

[SOLVED] Adding a string to the end of a varibale name.


Splash

Recommended Posts

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.  ;D

 

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  ;D

Splash

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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
// )


?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.