0

I have an array $customers, and want to print each value of the array to a text file. Array looks like this:

[0] = Sam, John, Rick
[1] = Jacob, Richard, David
[2] = Jesse, Frank, Louise

This is what I had in mind, but it doesn't seem to like implode:

$pos = 0;
    foreach ($customers as $customer)
    {
      $result = implode(" ",$customers[$pos]);
      //echo implode(" ",$customers[$pos]);
      file_put_contents('active.txt', $result);
      $pos = $pos + 1;
    }

The result I would expect in the text file is:

Sam, John, Rick
Jacob, Richard, David
Jesse, Frank, Louise

Can anyone explain how to do this? The goal is to have the array to appear comma delimited in a text file to export to Excel.

4
  • 1
    Check php.net/manual/en/function.fputcsv.php for creating a CSV file format Commented Apr 27, 2020 at 16:27
  • 1
    Why do you implode with space if it's comma you want. Not that it made any difference this time Commented Apr 27, 2020 at 16:45
  • Does your question have anything to do with what you asked in this one you asked? Commented Apr 27, 2020 at 16:48
  • file_put_contents() overwrites file contents if the FILE_APPEND flag is not set. You end up with only the last line in your file. Also I suggest not to use file_put_contents() in a loop because it opens and closes the file every time. This is a lot of I/O operations which take a lot of (unnecessary) time. Commented Apr 28, 2020 at 8:01

1 Answer 1

2

Each element of $customers is a single value, so rather than using a loop and imploding the strings, which also overwrite each other in the file.

You can just implode() the whole array with PHP_EOL for the line separator...

file_put_contents('active.txt', implode(PHP_EOL ,$customers));
Sign up to request clarification or add additional context in comments.

Comments

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.