What are some common strategies for formatting and displaying dynamically generated form data in PHP, especially when the structure of the data may vary?

When dealing with dynamically generated form data in PHP where the structure may vary, it's important to have a flexible strategy for formatting and displaying the data. One common approach is to use loops to iterate over the data and dynamically generate the HTML markup based on the structure of the data. Another strategy is to use conditional statements to check for different data types or structures and adjust the display accordingly. Using functions to handle the formatting logic can also make the code more modular and easier to maintain.

<?php
// Sample dynamically generated form data
$formData = [
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'age' => 30,
    'interests' => ['PHP', 'JavaScript', 'CSS'],
    'address' => [
        'street' => '123 Main St',
        'city' => 'Anytown',
        'state' => 'CA'
    ]
];

// Loop through the form data and generate HTML markup
foreach ($formData as $key => $value) {
    echo '<div>';
    echo '<label>' . ucfirst($key) . ': </label>';
    
    if (is_array($value)) {
        foreach ($value as $item) {
            echo '<span>' . $item . '</span>';
        }
    } else {
        echo '<span>' . $value . '</span>';
    }
    
    echo '</div>';
}
?>