Jump to content

Accessing variable from a string


phppup
Go to solution Solved by Barand,

Recommended Posts

I have variables as such

$var0 = "hello";
$var1 = "good bye";
$var2 = "back soon";

I get appropriate results when I do this

echo $var0;  echo $var1;  echo $var2;

Now, I want to get the r same esults using a created string like this

for($x=0; $x <3; $x++){
  $test = "\$var".$x; echo $test."<br>";
  }

But this only provides

$var0
$var1
$var2

How can I generate the respective variable elements so that they reflect their values?

Edited by phppup
Clean up post
Link to comment
Share on other sites

  • Solution

Put them in an array,

$var = [ "hello", "good bye", "back soon"];
for ($x=0; $x<3; $x++) {
        echo $var[$x] . '<br>';
} 

or

$var0 = "hello";
$var1 = "good bye";
$var2 = "back soon";

test($var0, $var1, $var2);


function test(...$vars)
{
    for ($x=0; $x<3; $x++) {
        echo $vars[$x] . '<br>';
    }
}

 

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.