我在foreach循环中设置变量,它们不在循环外回显

时间:2015-05-27 12:56:51

标签: php arrays foreach

我正在使用$ key =>设置数组$值。我使用它来设置表单提交的报告。我试图在foreach循环中设置一个php变量并在循环外使用它;但它没有用。有什么想法吗?

$formfields = array(
"Company Name" => "company",
"Contact Name" => "name",
"Address" => "address",
"City" => "city",
"State" => "state",
"Zip Code" => "zip",
"Phone Number" => "phone",
"Brand of Tool" => "brand",
"Tool Model" => "model",
"Description of Problem" => "description",
"Repair or Rebuild" => "repairorrebuild",
"Estimate or Repair & Return" => "estimateorrepair"
);



foreach ($formfields as $key => $value) { 
'$'. $value = htmlspecialchars($_POST[$value]); 
}

echo $company .' '. $name;

我已经通过回显foreach循环中的值进行测试,并且它们确实从表单返回值。所以我知道没有拼写错误。

1 个答案:

答案 0 :(得分:1)

要制作动态变量,您应该使用{}

foreach ($formfields as $key => $value) { 
  ${$value} = htmlspecialchars($_POST[$value]); 
}