1. <?php
  2. /**
  3. * Formats a collection into a string representation.
  4. *
  5. * @param array $collection The collection to format.
  6. * @param array $defaults An associative array of default values.
  7. * @return string The formatted string representation of the collection.
  8. */
  9. function formatCollection(array $collection, array $defaults = []): string
  10. {
  11. $output = '';
  12. foreach ($collection as $key => $value) {
  13. $formattedKey = htmlspecialchars(strval($key)); // Escape key for safety
  14. $defaultValue = $defaults[$key] ?? ''; // Get default value or empty string
  15. $output .= sprintf(
  16. ' %s: %s' . PHP_EOL,
  17. $formattedKey,
  18. htmlspecialchars(strval($value))
  19. );
  20. }
  21. return $output;
  22. }
  23. /**
  24. * Example Usage (for testing)
  25. */
  26. $myCollection = [
  27. 'name' => 'John Doe',
  28. 'age' => 30,
  29. 'city' => 'New York',
  30. ];
  31. $defaultValues = [
  32. 'occupation' => 'Unknown',
  33. 'country' => 'USA',
  34. 'email' => 'noemail@example.com',
  35. ];
  36. $formattedOutput = formatCollection($myCollection, $defaultValues);
  37. echo $formattedOutput;
  38. ?>

Add your comment