How can the concept of arrays be utilized to optimize the handling of multiple templates in PHP functions?

When handling multiple templates in PHP functions, utilizing arrays can optimize the process by storing all the template names in a single data structure. This allows for easier management and dynamic selection of templates based on specific conditions or parameters passed to the function.

// Define an array of template names
$templates = [
    'template1.php',
    'template2.php',
    'template3.php'
];

// Function to dynamically select and include a template based on a given index
function includeTemplate($index) {
    global $templates;
    
    if(array_key_exists($index, $templates)) {
        include $templates[$index];
    } else {
        echo "Template not found";
    }
}

// Example usage
includeTemplate(0); // Includes template1.php
includeTemplate(2); // Includes template3.php