简体   繁体   English

循环使用通用名称的变量

[英]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.我也对我应该使用的循环类型有些困惑,不确定“for”循环是否有效。 The only thing is I can't wrap my head around how php could interpret "on the fly" or fabricated variable.唯一的问题是我无法理解 php 如何解释“动态”或捏造的变量。 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>";
}

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 .有关更多信息,请参阅有关变量 Variables的 PHP 文档。

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>";
}

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

$a = "hell";
$b = "o";
$hello = "world";
echo ${$a . $b};

// output: world

You can use variable variables as:您可以将变量变量用作:

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

as I guess u not even need to declare $hello1 = "hello1".因为我想你甚至不需要声明 $hello1 = "hello1"。 coz the $counter is incrementing the numbers by its loop.因为 $counter 正在通过其循环递增数字。

<?php 
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo 'hello' . $counter . "\n";
}
?>

so this is enough to get the output as you want.所以这足以获得您想要的输出。

the output will be:-输出将是:-

hello1
hello2
hello3
hello4
hello5
hello6
hello7
etc...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM