如何为此循环?

时间:2018-03-19 09:19:42

标签: php loops for-loop

有可能这样做吗?这是我的代码:

$sponsor1 = "Sponsor 1";
$sponsor2 = "Sponsor 2";
$sponsor3 = "Sponsor 3";
$sponsor4 = "Sponsor 4";
$sponsor5 = "Sponsor 5";
for($i=1;$i<=5;$i++) {
if($sponsor.$i){
echo $sponsor.$i;
echo "<br>";
}}

我希望上面的循环可以像这样显示。我想要这样的东西:

Sponsor 1
Sponsor 2
Sponsor 3
Sponsor 4
Sponsor 5

3 个答案:

答案 0 :(得分:3)

您可以使用PHP变量变量构建变量,请在此处阅读: http://php.net/manual/en/language.variables.variable.php

$sponsor1 = "Sponsor 1";
$sponsor2 = "Sponsor 2";
$sponsor3 = "Sponsor 3";
$sponsor4 = "Sponsor 4";
$sponsor5 = "Sponsor 5";
for($i=1;$i<=5;$i++) {
   $v = 'sponsor'.$i;
   echo $$v;
   echo "<br>";
}

注意$$v

答案 1 :(得分:3)

有三种可能的解决方案:

1.创建数组并迭代它。 (的 最佳

$sponsor_array = ["Sponsor 1","Sponsor 2","Sponsor 3","Sponsor 4","Sponsor 5"];
foreach($sponsor_array as $sponsor){
 echo $sponsor;
 echo PHP_EOL;
}

输出: - https://eval.in/974403

2.直接使用for()循环( 更好

<?php

for($i=1;$i<=5;$i++) {

  echo "Sponsor ".$i;
  echo PHP_EOL;
}

输出: - https://eval.in/974401

3.使用Variables variable概念( 不推荐您的案例

$sponsor1 = "Sponsor 1";
$sponsor2 = "Sponsor 2";
$sponsor3 = "Sponsor 3";
$sponsor4 = "Sponsor 4";
$sponsor5 = "Sponsor 5";
for($i=1;$i<=5;$i++) {
   $v = 'sponsor'.$i;
   echo $$v;
   echo "<br>";
}

输出: - https://eval.in/974405

答案 2 :(得分:1)

正确的解决方案是使用数组。

$sponsors = [
    "Sponsor 1",
    "Sponsor 2",
    "etc"
];

foreach ($sponsors as $thisSponsor) {
    echo "$thisSponsor<br />\n";
}

如果由于某种原因您不能直接使用数组,您可以始终执行以下操作:

foreach ([$sponsor1, $sponsor2, $sponsor3, $sponsor4, $sponsor5] as $thisSponsor) {