Hell all, am new here and am an intermediate php developer. I am having a silly proble am guessing the solution will be a simple syntax buh i dont know how to fix it.

Okay here is it..

Lets say i have a variable in php eg


now i do something a foreach loop

foreach($file as $file)
    //get $first_data variable, append $d to bottom part of it 
    //without overwriting the content of the variable
    //lets say the loop runs ten times and each time $d has diffrent contents
    //i want all the contents to be added to the $first_data variable
file_put_contents("test_contents.txt", $first_data);

thanks for any help.

Member Avatar

I am having a silly proble am guessing the solution will be a simple syntax buh i dont know how to fix it.

I'm a bit confuse what you trying to ask?

The code doesn't make any sense because it's only 3 lines and it's hard to understand what you want to do.

Can you provided a little more code.

Base on that small code you want to write on txt file:

First you need to $_POST data and used fwrite() function:


 $File = "test_contents.txt"; 
 $Handle = fopen($File, 'w');

Like LastMitch explained, without having more context it's unclear exactly what you are after.

If you're just trying to append the value in $d to the value in $first_data, you would use the contatenation operator. $first_data .= $d; or $first_data = $first_data . $d;

To answer your question, here is an example. I hope the example I'm giving will help you.


$name = "Dani";

if($name== "Dani"){
    echo $name;         => this will output Dani
    $name .= " Web";    => this will concatenate the string " Web" to the "Dani"

echo $name;    => this will output "Dani Web"


Thanks all for the tips and tricks..@rotten69 won't the foreach loop affect the data concatenated?...I mean if file_a value is a, file_b value is b and so on, I want a situation that at the end of the loop and the file is saved to the txt file, it would have content like "daniabcdef" with all the value of the diffrent file contents concatenated with the original value of $first_data.

@lastmitch...thank you for your snippet I will try to implement this and see how it goes.

@dcdruck..thanks I really appreciate this!!

Member Avatar
foreach($file as $file)

Looks odd. Expanding on dcdruck, try this:

$file = array('myfile1.txt','myfile2.txt',...);

foreach($file as $f){
        $file_data .= $d;
file_put_contents("test_contents.txt", $first_data);

Of course, this will overwrite test_contents.txt. If you do not want this, place test_contents.txt as your first file in the $file array.

u can create an array

foreach($file as $file){
    $first_data[$i] = $d;
file_put_contents("test_contents.txt", $first_data);

and include all you need in pos