0

I have created two arrays and I want all the information from both to save to a .txt file. I want it to save in the format ('DATE' 'RAINFALL') inside the file. I tried many sources for help and I still can't get it to save. How can I do it? Thank you

The format inside the txt file

This is the format inside the .txt file I want

Code I currently have:

$rainf_array = array($rainf0, $rainf1, $rainf2, $rainf3, $rainf4, $rainf5, $rainf6 );

    $date_array = array($date0, $date1, $date2, $date3, $date4, $date5, $date6 );


   //Input value is saved to the file

   {
     $fileHandle = fopen($fileName, "w");

      fwrite($fileHandle, $date_array .'' . $rainf_array . ",\n" );


     fclose($fileHandle);
   }
3
  • 1
    You could use implode or iterate over the array and concatenate to a string... or use a CSV parser, something like php.net/manual/en/function.fputcsv.php, that would be a CSV though although maybe you can change delimiter to a space (I would use some delimiter). Commented Oct 2, 2020 at 14:27
  • Yeah but I want inside the file's format to look like this ('Date' 'Rainfall'). How do I make it look like that? Commented Oct 2, 2020 at 15:07
  • You should encapsulate the values in quotes, and use a delimiter. This is going to be hard to use in the future. I'd have 'yyyy-mm-dd', '##' or 'yyyy-mm-dd', ##. Commented Oct 2, 2020 at 15:29

1 Answer 1

1

My suggestion:

$date_array = array($date0, $date1, $date2, $date3, $date4, $date5, $date6);
$rainf_array = array($rainf0, $rainf1, $rainf2, $rainf3, $rainf4, $rainf5, $rainf6);

$combined = array_combine($date_array, $rainf_array);

foreach ($combined as $key => $value) {
  $input .= $key . ' ' . $value . "\n";
}

Then save $input into the file.

Sign up to request clarification or add additional context in comments.

2 Comments

Just a quick question I didn't understand the '$combined' function? Is there anywhere I could get more clarification? Thank you
@vorandasb The array_combine function creates an array ($combined) by using one array ($date_array) for keys and another ($rainf_array) for its values. See here: php.net/manual/en/function.array-combine.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.