在内部添加循环' echo'用PHP

时间:2015-01-05 07:18:37

标签: php loops

PHP echo中是否可以包含for loop? 像这样:

echo "This are the list" . for($i=0; $i<=$count; $i++) { echo $variable1 . $variable2} . "End";

我的代码是这样的。

但我仍然遇到错误。

4 个答案:

答案 0 :(得分:5)

循环不要进入echo语句。将它们分开

echo "This are the list";
for($i=0; $i<=$count; $i++)
{
 echo $variable1 . $variable2;
} 
echo "End";

将通过以下方式生成更易读的输出版本:

echo "This is the list: <br>";
for($i=0; $i<=$count; $i++)
{
 echo $variable1. " ". $variable2."<br>";
} 
echo "End";

答案 1 :(得分:2)

没有。 echo only accepts strings;它不能像函数或方法那样充当代码块。但你当然可以这样做:

echo "This are the list";
for ($i=0; $i<=$count; $i++) {
    echo $variable1 . $variable2;
}
echo "End";

答案 2 :(得分:0)

没有你做不到你不能在echo语句中循环,你可以这样做:

$text = 'This are the list ';

for($i=0; $i<=$count; $i++){
    $text .=  $variable1.$variable2;
}

$text .= 'End';

echo $text;

答案 3 :(得分:0)

不,它不会像那样工作。

您有两种选择。

选项1

$temp_string = '';
for ($i=0; $i<=$count; $i++)
{
 $temp_string .= $variable1 . $variable2;
}
echo "This are the list".$temp_string;

选项2

echo "This are the list";
for($i=0; $i<=$count; $i++)
{
 echo $variable1 . $variable2;
} 
echo "End";