Reputation: 129
$files = array("post", "name", "date");
$post = $_POST["comment"];
$name = $_POST["name"];
$date = date("H:i F j");
foreach ($files as $x) {
$file = fopen("db/$x.txt", "a");
$x = "$" . $x;
fwrite($file, $x);
fclose($file);
}
Trying to put values of $post, $name
and $date
into post.txt, name.txt and date.txt files respectively, but it puts literals "$post"
into post.txt and so forth. Please help!
Upvotes: 1
Views: 78
Reputation: 67
You are using $x = "$".$x which doesn't give you the values you want. Try this instead:
$files = [
'comment' => $_POST['comment'],
'name' => $_POST['name'],
'date' => date('H:i F j')
];
foreach($files as $name => $value) {
$file = fopen("db/$name.txt", "a");
fwrite($file,$value);
}
Upvotes: 1
Reputation: 31749
Try with variable of variable
-
foreach ($files as $x) {
$file = fopen("db/$x.txt", "a");
$x = $$x;
fwrite($file, $x);
fclose($file);
}
A variable variable takes the value of a variable and treats that as the name of a variable.
You will get the details here
Upvotes: 1
Reputation: 27092
Use array instead, it's the right choice.
$values = array(
'comment' => $_POST["comment"],
'name' => $_POST["name"],
'date' => date("H:i F j")
);
foreach ($values as $x) {
$file = fopen("db/$x.txt", "a");
fwrite($file, $x);
fclose($file);
}
Upvotes: 1