如何在字符串中包含尚未定义的变量?PHP

mat*_*att 2 php variables

为了执行更少的数据库查询和清晰的代码,我想在字符串中包含一个尚未定义的变量.稍后在页面中,将声明变量并打印和评估字符串.我该怎么做呢?

$str="This $variable is delicious";

$array=array("Apple","Pineapple","Strawberry");

foreach($array as $variable)
{
  print "$str";
}
Run Code Online (Sandbox Code Playgroud)

Nul*_*ion 13

您可以使用printf()(或者sprintf()如果您不想回应它):

$str = 'This %s is delicious';

foreach ($array as $variable) {
    printf($str, $variable);
}
Run Code Online (Sandbox Code Playgroud)