1. <?php
  2. /**
  3. * Formats a list of items into a simple, readable output.
  4. *
  5. * @param array $items An array of items to format.
  6. * @param string $label (optional) A label to prepend to the list.
  7. * @return string The formatted list as a string.
  8. */
  9. function formatList(array $items, string $label = ""): string {
  10. if (empty($items)) {
  11. return "[]"; // Return empty array if input is empty
  12. }
  13. $output = "";
  14. $output .= ($label . ": ") . "[" . PHP_EOL; // Add label and opening bracket
  15. foreach ($items as $item) {
  16. $output .= "- " . var_export($item, true) . PHP_EOL; // Format each item with a dash
  17. }
  18. $output .= "]" . PHP_EOL; // Add closing bracket
  19. return $output;
  20. }
  21. //Example Usage:
  22. // $myList = ['apple', 'banana', 'cherry'];
  23. // echo formatList($myList, "Fruits");
  24. // $emptyList = [];
  25. // echo formatList($emptyList, "Empty List");
  26. ?>

Add your comment