Loop through variables with a common name

At first glance, I think you can get what I'm trying to do. I want to encode variables with the same name but with a numerical prefix. I also had some confusion about the loop that I should use, but not sure if the for loop would work. The only thing I can’t wrap up is how php can interpret on the fly or a fabricated variable. In some problems, a line appeared with a dollar sign. Thanks in advance!

$hello1 = "hello1"; $hello2 = "hello2"; $hello3 = "hello3"; $hello4 = "hello4"; $hello5 = "hello5"; $hello6 = "hello6"; $hello7 = "hello7"; $hello8 = "hello8"; $hello9 = "hello9"; $hello10 = "hello10"; for ( $counter = 1; $counter <= 10; $counter += 1) { echo $hello . $counter . "<br>"; } 
+4
source share
3 answers

Try ${"hello" . $counter} ${"hello" . $counter}

 $a = "hell"; $b = "o"; $hello = "world"; echo ${$a . $b}; // output: world 
+6
source

In general, he frowned, as it makes the code much more difficult to read and follow, but you can use one variable value as another variable name:

 $foo = "bar"; $baz = "foo"; echo $$baz; // will print "bar" $foofoo = "qux"; echo ${$baz . 'foo'}; // will print "qux" 

See the PHP documentation for variable variables for more information.

However, as I mentioned, this can lead to very difficult to read code. Are you sure you can't just use an array?

 $hello = array( "hello1", "hello2", // ... etc ); for($hello as $item) { echo $item . "<br>"; } 
+8
source

You can use variable variables like:

 for ( $counter = 1; $counter <= 10; $counter += 1) { echo ${'hello' . $counter } , '<br>'; } 
+2
source

All Articles