DEV Community

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

Posted on • Updated on

How To Print & Write Array Values to Files in PHP

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/php/how-to-print-write-array-values-to-files-in-php

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

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.

<?php

$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

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

Thanks for reading. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/php/how-to-print-write-array-values-to-files-in-php if you want to download this code.

Happy coding :)

Top comments (1)

Collapse
 
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 : php.net/manual/fr/function.file-pu...