phppup Posted September 10, 2022 Share Posted September 10, 2022 (edited) 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 September 10, 2022 by phppup Clean up post Quote Link to comment https://forums.phpfreaks.com/topic/315307-accessing-variable-from-a-string/ Share on other sites More sharing options...
mac_gyver Posted September 10, 2022 Share Posted September 10, 2022 by using an array instead of a series of name-numbered variables. Quote Link to comment https://forums.phpfreaks.com/topic/315307-accessing-variable-from-a-string/#findComment-1600393 Share on other sites More sharing options...
Solution Barand Posted September 10, 2022 Solution Share Posted September 10, 2022 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>'; } } Quote Link to comment https://forums.phpfreaks.com/topic/315307-accessing-variable-from-a-string/#findComment-1600394 Share on other sites More sharing options...
phppup Posted September 10, 2022 Author Share Posted September 10, 2022 (edited) 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 September 10, 2022 by phppup Quote Link to comment https://forums.phpfreaks.com/topic/315307-accessing-variable-from-a-string/#findComment-1600395 Share on other sites More sharing options...
requinix Posted September 11, 2022 Share Posted September 11, 2022 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 Quote Link to comment https://forums.phpfreaks.com/topic/315307-accessing-variable-from-a-string/#findComment-1600399 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.