J. Doe J. Doe - 2 months ago 9
PHP Question

Is it possible to use File_put_contents($fileName, $array) so that each item in the array gets put on a new line?

I am trying to rewrite a file with the contexts of an array but I want each item in the array to be on separate line. Is this possible to do?

I currently have the following:

file_put_contents('file.txt',$tempArray);


The array has the following contents:

$tempArray = ["xyz","zyx", "123"]


and I want the file to look like this in the end:

xyz
zyx
123


but I am getting it all on one line currently

Answer

Do file_put_contents('file.txt',implode(PHP_EOL,$tempArray)); and you are fine.

  • implode takes a seperator and array-values then concates them like: implode('+',array(1,2)) becomes 1+2

  • PHP_EOL is an predefined constant from php that defines "\n" on linux and "\r\n" on windows

Comments