$i = 1
echo '
<p class="paragraph$i">
</p>
'
++i
我想在一个输出的字符串中插入一个变量。上面的代码无法工作。我如何将一个PHP变量迭代到一个echo字符串中?
单引号内无法解析 PHP 变量,可以使用双引号或使用点号来扩展 echo。
$variableName = 'Ralph';
echo 'Hello '.$variableName.'!';
或者
echo "Hello $variableName!";
而在你的情况下:
$i = 1;
echo '<p class="paragraph'.$i.'"></p>';
++i;
或者
$i = 1;
echo "<p class='paragraph$i'></p>";
++i;
当在字符串中使用变量时,始终使用双引号,并转义除起始和结束引号以外的任何其他双引号。您还可以像下面这样使用括号,以便更轻松地查找字符串中的变量并使其看起来更清洁。
$var = 'my variable';
echo "I love ${var}";
或者$var = 'my variable';
echo "I love {$var}";
上面的代码将返回以下结果:我爱我的变量。在单引号中不会发生变量插值。您需要使用双引号,如下所示:
$i = 1
echo "<p class=\"paragraph$i\"></p>";
++i;
echo '<p class="paragraph'.$i.'"></p>'
echo '<p class="paragrah"' . $i . '">'
echo '<p class="paragraph'.$i.'"></p>';
$x = '+3';
echo "1+2$x";
双引号(")允许您直接将变量放在其中。
第二种方法:
$x = '+3';
echo '1+2'.$x;
如果由于某种原因您不想使用双引号,请使用这种方法。 点(.)表示“添加”。 因此,如果您想要添加类似于1 + 2 + 3 + 4 + 5的内容,并且在中间有变量,则只需执行以下操作:
$x = '+3';
echo '1+2'.$x.'+4+5';
$x = '+3';
$y = '+4';
$z = '+5';
echo "1+2${"x".$y.$z}";
Output: 1+2+3+4+5
$y
和$z
添加到$x
中;{}
在渲染未定义变量之前优先处理其中的内容。
这对于调用如下的函数非常有用:
//Add the Get request to a variable.
$x = $_GET['tool'];
//Edit: If you want this if to contain multiple $xresult's change the if's
//Conditon in the "()" to isset($get). Simple. Now just add $xresultprogram
//or whatever.
if($x == 'app') {
$xresultapp = 'User requested tool: App';
}
//Somewhere down far in HTML maybe...
echo ${"xresult".$x}; // so this outputs: $xresultapp's value
//Note: doing ${"xresult".$_GET['tool']} directly wont work.
//I believe this is because since some direct non-echo html was loaded
//before we got to this php section it cant load cause it has already
//Started loading client side HTML and JS.
example.com?tool=app
,那么这将输出$xresultapp
的“用户请求的工具:App”。您可以使用else语句进行修改,以定义当请求值为“app”以外的其他值时发生的情况。请记住,大小写敏感,因此如果他们请求大写的“App”,它不会输出$xresultapp
。使用双引号:
$i = 1;
echo "
<p class=\"paragraph$i\">
</p>
";
++i;
$i = 1;
echo "<p class='paragraph{$i}'></p>";
$i++;
$i = 1
echo '<p class="paragraph'.$i.'"></p>';
++i;