W3docs

How to output (to a log) a multi-level array in a format that is human-readable?

There are a few different ways you can output a multi-level array in a human-readable format, depending on what you mean by "human-readable" and what you want to achieve.

There are a few different ways you can output a multi-level array in a human-readable format, depending on what you mean by "human-readable" and what you want to achieve. Here are a few options:

  1. You can use print_r() function in PHP to output the contents of an array in a way that is easy for humans to read. This function will output the array in a nested, tree-like structure, with each level of the array indented to show its hierarchy.
  2. If you want to output the array as a string of PHP code that can be easily pasted back into a PHP script, you could use var_export(). Note that this generates PHP syntax rather than a clean log format, so it's better suited for code generation than logging.
  3. Another option is to use json_encode() with the JSON_PRETTY_PRINT flag to convert the array into a formatted JSON string, which can be easily read and understood by humans. JSON is a popular data interchange format that is used to transmit data between a server and a web application.
  4. If you want to output the array to the command line or a log, you could use var_dump() function in PHP, which will output the contents of the array in a format that is easy for humans to read. This function will output the type and value of each element in the array.

To write the output directly to a log file, you can combine these functions with PHP's file handling. Here is a practical example using print_r():

$array = ['level1' => ['level2' => ['value']]];
$logFile = '/path/to/log.txt';
// The second parameter `true` returns the output as a string instead of printing it
file_put_contents($logFile, print_r($array, true) . PHP_EOL, FILE_APPEND);

I hope this helps! Let me know if you have any questions.