Print array to a file

To print an array to a file in PHP, you can use the file_put_contents() function, which writes a string to a file. You can use json_encode() to convert the array to a JSON string, and then write that string to a file. Here's an example:

<?php

$array = ['apple', 'banana', 'orange'];
$json = json_encode($array);
file_put_contents('file.txt', $json);

This will create a file called file.txt in the current directory, and write the JSON string ["apple","banana","orange"] to it.

Watch a course Learn object oriented PHP

You can also use the fopen(), fwrite(), and fclose() functions to write to a file. Here's an example:

<?php

$array = ['apple', 'banana', 'orange'];
$json = json_encode($array);

$file = fopen('file.txt', 'w');
fwrite($file, $json);
fclose($file);

This will have the same effect as the previous example.

If you want to write the array to the file in a different format, you can use a loop to iterate over the array and write each element to the file, using fwrite() or file_put_contents() to write each element to the file.