<?php
/**
* Formats a list of items into a simple, readable output.
*
* @param array $items An array of items to format.
* @param string $label (optional) A label to prepend to the list.
* @return string The formatted list as a string.
*/
function formatList(array $items, string $label = ""): string {
if (empty($items)) {
return "[]"; // Return empty array if input is empty
}
$output = "";
$output .= ($label . ": ") . "[" . PHP_EOL; // Add label and opening bracket
foreach ($items as $item) {
$output .= "- " . var_export($item, true) . PHP_EOL; // Format each item with a dash
}
$output .= "]" . PHP_EOL; // Add closing bracket
return $output;
}
//Example Usage:
// $myList = ['apple', 'banana', 'cherry'];
// echo formatList($myList, "Fruits");
// $emptyList = [];
// echo formatList($emptyList, "Empty List");
?>
Add your comment