2012-09-22 53 views
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变量?

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

感谢

+0

就使$ WELCOME_MESSAGE分配在循环内。 – Tushar

回答

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>"; 
} 
+0

问题是我的$ welcome_message比我的简单例子要大得多。如果它的大,在一个循环中,我想在性能问题试图在循环之外。 – phpmysqlguy

+0

@phpmysqlguy:您需要在每次迭代中将变量替换为消息。无论你如何选择这样做,事实是,你不能神奇地避免这种情况。 – Jon

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>"; 
} 
+0

如果需要定制$ welcome_message的不同部分,如何处理它?例如“你好,%s,现在温带是” – phpmysqlguy

+0

阅读'* printf'函数族(start [here](http://php.net/manual/en/function.sprintf.php) )。简而言之:您可以在一个字符串中包含多个占位符,并且它们可以具有不同的格式。你的代码需要一个字符串占位符('%s'),但其他的则需要小数,浮点数,字符等等。 – Maerlyn

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>"; 
} 
+0

我想我没有提到$ welcome_message要大得多,并且有很多部分需要改变。这并不像我放手那么简单,我试图简化这个例子的目的。 – phpmysqlguy