Jump to content

Accessing variable from a string


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
https://forums.phpfreaks.com/topic/315307-accessing-variable-from-a-string/
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>';
    }
}

 

I have

function xyz($var0, $var1, $var2)

and I want to see their values visually. I want to generate  FOR-style statement to automate this process.

Did creating a function with elements assigned inadvertently create an array?

Edited by phppup

What mac_gyver and Barand are trying to tell you is that this idea you have is the wrong way of doing... whatever you want.

As in, don't use multiple arguments named "varX" and instead use a single argument that takes an array.

xyz(1, 2, 3); // no

xyz([1, 2, 3]); // yes

 

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.