Create multiple files in PHP using foreach loop for array created using the file () function

advertisements

I am trying to create multiple files in PHP using a foreach loop. The foreach loop reads the contents of an array, which is formed using file() function from a text(.txt) file. The loop is supposed to create a [.php] file with EACH of the value in the array, but it is creating the file for ONLY the LAST value in the array.

<?php
$user_list=file('users.txt');
$n=0;
foreach ($user_list as $user[$n]) {
if(!file_exists("Users/".$_POST[username]."-".$user[$n].".php")){
$file_c=fopen("Users/".$_POST[username]."-".$user[$n].".php", 'a+');
fwrite($file_c,"Content");
}
$n++;
}
?>


If you work with multiple fwrite(), need to be close file handler by fclose() after writing file was completed:

<?php
    $user_list=file('users.txt');

    foreach ($user_list as $user) {
        if(!file_exists("Users/".$_POST[username]."-".trim($user).".php")){
            $file_c=fopen("Users/".$_POST[username]."-".trim($user).".php", 'a');
            fwrite($file_c,"Content");
            fclose($file_c);
        }

    }
?>