出于某种原因,我似乎无法围绕这个问题.
$welcome_message = "Hello there $name";
$names_array = array("tom", "dick", "harry");
foreach ($names_array as $this_name) {
$name = $this_name;
echo $welcome_message."<br>";
}
Run Code Online (Sandbox Code Playgroud)
如何每次更新$ welcome_message中的$ name变量?
使用变量但我似乎无法使其工作.
谢谢
也许你在寻找sprintf?
$welcome_message = "Hello there %s";
$names_array = array("tom", "dick", "harry");
foreach ($names_array as $this_name) {
echo sprintf($welcome_message, $this_name), "<br>";
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为$welcome_message在开始时只评估一次($name可能仍未定义).你不能在里面"保存"所需的表格,$welcome_message并随意"扩展"它(除非你使用eval,这是完全避免的东西).
移动设置$welcome_message在循环内部的行:
$names_array = array("tom", "dick", "harry");
foreach ($names_array as $this_name) {
$welcome_message = "Hello there $this_name";
echo $welcome_message."<br>";
}
Run Code Online (Sandbox Code Playgroud)