简体   繁体   中英

I set variables inside foreach loop and they are not echoing outside the loop

I am setting up an array with $key => $value. I am using this to set up a report from a form submission. I am trying to set a php variable inside the foreach loop and use it outside the loop; however, it isn't working. Any ideas why?

$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;

I've tested by echoing the value's inside the foreach loop and they do return the values from the form. So I know there are no typo's.

To make dynamic variables you should use {}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM