When outputting the content data of array to a file in PHP, simply pass the data variable of array type to file_put_content() or fwrite() function to write the data to the file may not return the desired result. Instead of human-readable information of the array that shows shows types or keys and elements, only the word “Array” is written to the file.

When displaying to screen or presentation media, programmer normally uses print_r() function to display the complete data of the array in a way that’s readable by humans.

In order to write the content and data of array to the file, we can use the print_r() or var_export() functions to return the output instead of printing it.

For example for the syntax,

$array_content = print_r($array, TRUE);

Or,

$array_content = var_export($array, TRUE);
Note
“TRUE” in the print_r() function is for “return” parameter that instructs the function to return the information rather than print it.

It’s possible to directly return the results when writing to file:

file_put_contents('filename.txt', print_r($array, TRUE));

Or,

file_put_contents('filename.txt', var_export($array, TRUE));