Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

php - Loop through variables with common name

At first glance I think you can get what I'm trying to do. I want to loop though variables with the same name but with a numerical prefix. I also had some confusion about the kind of loop I should use, not sure if a "for" loop would work. The only thing is I can't wrap my head around how php could interpret "on the fly" or fabricated variable. Ran into some trouble with outputting a string with a dollar sign as well. 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>";
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's generally frowned upon, since it makes code much harder to read and follow, but you can actually use one variable's value as another variable's name:

$foo = "bar";
$baz = "foo";

echo $$baz; // will print "bar"

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

For more info, see the PHP documentation on variable Variables.

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

$hello = array(
    "hello1",
    "hello2",
    // ... etc
);

foreach($hello as $item) {
    echo $item . "<br>";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...