DEV Community 👩‍💻👨‍💻

Cover image for How To Print & Write Array Values to Files in PHP
Code And Deploy
Code And Deploy

Posted on

How To Print & Write Array Values to Files in PHP

Originally posted @ visit and download the sample code:

In this post, I will share a short and simple code on how to print and write array values to files in PHP. If you have a task or problem that needs to write the array value to a file then this is for you. In this example, I'm using file_put_contents() to put the value to a file. And PHP_EOL to newline after loop the array values.


$contents = '';

$programmingLanguages = ['PHP', 'PYTHON', 'C#', 'C++'];

foreach ($programmingLanguages as $programmingLanguage) {
    $contents .= $programmingLanguage.PHP_EOL;

file_put_contents('filename.txt', $contents, true);

Enter fullscreen mode Exit fullscreen mode

Thanks for reading. I hope this tutorial can help you. Kindly visit here if you want to download this code.

Happy coding :)

Top comments (1)

klnjmm profile image
Jimmy Klein

Simple solution, no need to loop :

$programmingLanguages = ['PHP', 'PYTHON', 'C#', 'C++'];
$contents = implode(PHP_EOL, $programmingLanguages).PHP_EOL;

file_put_contents('filename.txt', $contents);
Enter fullscreen mode Exit fullscreen mode

And file_put_contents don't accept boolean at third parameters, it's better to use flags :

We are hiring! Do you want to be our Senior Platform Engineer? Are you capable of chipping in across sysadmin, ops, and site reliability work, while supporting the open source stack that runs DEV and other communities?

This role might just be for you!

Apply now