Is there any way in PHP to open a file based on a variable for the filename? Basically what I want to is this:
$file = file('data.txt');
$needle = array("one", "two", "three");
$haystack = array("one", "three");
foreach($needle as $value){
$pos = strpos($haystack, $value);
if($pos !== false){
$filename = "$value.txt";
file_put_contents($filename, $file);
}
The values of $needle are the names of .txt files. It works up until file_put_contents. $filename is not valid and I have searched all over for a solution to this and tried everything I can think of. I want to load the array value, say “one” with the .txt extension as a filename, depending on if the value was found in the haystack. Is there any way to do this without doing an if statement for each filename? I would rather handle it with a loop if possible.
Edited to swap the parameters.
Edit, new code:
$data = file_get_contents('data.txt');
$needle = array("one", "two", "three");
$haystack = array("one", "three");
$files = array_intersect($needle, $haystack);
foreach ($files as $value) {
$newfilename = "$value.txt";
var_dump($newfilename);
file_put_contents($newfilename, $data);
}
You mixed up the parameters of file_put_contents():
So you need to swap them:
Second thing is, that you’re doing a strpos() on an array, but that function is (as its name says) for strings – what you want is in_array():
You can even enhance this a bit more by using array_intersect() – that gives you an array of all the value from $needle that are also in $haystack. I think that’s what you were asking for to avoid the if statement: