<?php
/**
* Formats a collection into a string representation.
*
* @param array $collection The collection to format.
* @param array $defaults An associative array of default values.
* @return string The formatted string representation of the collection.
*/
function formatCollection(array $collection, array $defaults = []): string
{
$output = '';
foreach ($collection as $key => $value) {
$formattedKey = htmlspecialchars(strval($key)); // Escape key for safety
$defaultValue = $defaults[$key] ?? ''; // Get default value or empty string
$output .= sprintf(
' %s: %s' . PHP_EOL,
$formattedKey,
htmlspecialchars(strval($value))
);
}
return $output;
}
/**
* Example Usage (for testing)
*/
$myCollection = [
'name' => 'John Doe',
'age' => 30,
'city' => 'New York',
];
$defaultValues = [
'occupation' => 'Unknown',
'country' => 'USA',
'email' => 'noemail@example.com',
];
$formattedOutput = formatCollection($myCollection, $defaultValues);
echo $formattedOutput;
?>
Add your comment