Jump to content

Recommended Posts

Hi again.

 

I have a for() loop, where $i increments to 10.

 

Inside the loop, i wanna create a variable(say $var_);, with $i appended at the end.

So everytime the loop goes around, i'd get $var_1, $var_2, $var_3.........$var_10.

 

doing $var_$i = 'string' doesn't work.

I am concatenating, but not to output. I wanna concatenate to create a variable

 

here's my code

 

for($i = 0; $i <= 10; $i++) {
        // i wanna do something like this.  So it would create 10 variables. $var_0, $var_1, $var_2....etc
$var_ $i = "some string";

}
}
?>

Use:

$i = 10;

$var_10 = 'hello';

echo ${'var_' . $i};

 

EDIT Beaten to it by tippy, But anyways if you want to use variables value as part of a variables name you'll have to use variable variables, which what the above is

<?php
for ($i=1 ; $i <= 10 ; $i++)
{
    $varname = "var_$i";
    $$varname = $i;
}

echo $var_5;             // --> 5
?>

 

As said, I can't see why anyone would want to do this now the array has been invented.

<?php
for ($i=1 ; $i <= 10 ; $i++)
{
    $varname = "var_$i";
    $$varname = $i;
}

echo $var_5;             // --> 5
?>

 

As said, I can't see why anyone would want to do this now the array has been invented.

 

I already have a multidimensional array(3 arrays nesting). don't want more though.

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.