How can the cleanID function described in the forum thread help ensure valid and unique IDs in HTML generated from PHP data structures?

The cleanID function can help ensure valid and unique IDs in HTML generated from PHP data structures by removing any characters that are not allowed in HTML IDs and ensuring that each ID is unique within the generated HTML. This function can be used to sanitize user input or dynamically generated IDs to prevent conflicts and ensure compliance with HTML standards.

function cleanID($id) {
    // Remove any characters that are not allowed in HTML IDs
    $cleaned_id = preg_replace('/[^A-Za-z0-9_]/', '', $id);
    
    // Ensure the ID is unique by appending a random number if necessary
    $unique_id = $cleaned_id;
    $counter = 1;
    while (in_array($unique_id, $existing_ids_array)) {
        $unique_id = $cleaned_id . '_' . $counter;
        $counter++;
    }
    
    return $unique_id;
}