2

由于某种原因,我似乎无法解决这个问题。

$welcome_message = "Hello there $name";

$names_array = array("tom", "dick", "harry");

foreach ($names_array as $this_name) {
    $name = $this_name;
    echo $welcome_message."<br>";
}

如何每次更新 $welcome_message 中的 $name 变量?

使用可变变量,但我似乎无法使其工作。

谢谢

4

3 回答 3

6

也许你正在寻找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>";
}
于 2012-09-22T17:01:29.570 回答
5

这不起作用,因为$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>";
}
于 2012-09-22T17:00:45.530 回答
3

你可以像这样每次更新 $welcome_message....

$welcome_message = "Hello there ".$name;

现在代码将是这样的......

$welcome_message = "Hello there ";

$names_array = array("tom", "dick", "harry");

foreach ($names_array as $this_name) {
echo $welcome_message.$this_name"<br>";
}
于 2012-09-22T17:01:36.763 回答