How can an associative array be dynamically generated in PHP to efficiently handle varying parameters for URL construction?

When constructing URLs with varying parameters, an associative array can be dynamically generated in PHP to efficiently handle these parameters. This allows for flexibility in adding or removing parameters without needing to modify the URL construction code each time. By dynamically generating the associative array based on the parameters provided, the code becomes more scalable and easier to maintain.

// Dynamically generate an associative array for URL parameters
$params = array();

// Add parameters as needed
$params['param1'] = 'value1';
$params['param2'] = 'value2';

// Construct the URL with the parameters
$url = 'https://example.com/api?' . http_build_query($params);

echo $url;