How can environment variables be effectively utilized to manage configuration settings in PHP applications for different environments?

Environment variables can be effectively utilized to manage configuration settings in PHP applications for different environments by setting different values for the variables based on the environment (e.g., development, staging, production). This allows for easy configuration changes without modifying the codebase and helps keep sensitive information secure.

// Set environment variable based on the server environment
$env = getenv('ENVIRONMENT') ?: 'development';

// Configuration settings based on environment
switch ($env) {
    case 'development':
        $dbHost = 'localhost';
        $dbUser = 'root';
        $dbPass = 'password';
        break;
    case 'production':
        $dbHost = 'productionhost';
        $dbUser = 'produser';
        $dbPass = 'prodpassword';
        break;
    default:
        // Default configuration settings
        $dbHost = 'localhost';
        $dbUser = 'root';
        $dbPass = 'password';
}

// Use the configuration settings as needed