How to change the Web Property ID of Google Analytics per hostname / domain / language in Drupal 8

This can be done for almost anything not just for Google Analytics, so what we are going to do here is override exportable configs in settings.php so we can add conditional logics to it.

So for example if you want to override the Google Analytics Web Property ID in Drupal 8, you can use the following.

$config['google_analytics.settings']['account'] = 'UA-XXXXXX-X';

How you do conditional, let's say you want your Google Analytics Web Property ID is available only in your production environment, here is how you do that for Acquia cloud or Pantheon.

For Acquia:

/**
 * Set google analyics tracking code for production.
 */
if (isset($_ENV['AH_SITE_ENVIRONMENT'])) {
  if ($_ENV['AH_SITE_ENVIRONMENT'] == 'prod') {
    $config['google_analytics.settings']['account'] = 'UA-XXXXXXXX-Z';
  }
}

For Pantheon:

if (PANTHEON_ENVIRONMENT == 'dev') {
  $config['google_analytics.settings']['account'] = 'UA-XXXXXXXX-X';
}
else if (PANTHEON_ENVIRONMENT == 'test') {
  $config['google_analytics.settings']['account'] = 'UA-XXXXXXXX-Y';
}
else if (PANTHEON_ENVIRONMENT == 'live') {
  $config['google_analytics.settings']['account'] = 'UA-XXXXXXXX-Z';
}

In addition to those you can use different conditional logics too.

// Override Google Analytics Web Property ID per hostname. 
// Hostnames need to be lower-case!
switch ($_SERVER['HTTP_HOST']) {
  case 'www.example.com':
  case 'www.example.net':
  case 'forum.example.net':
    $config['google_analytics.settings']['account'] = 'UA-XXXXXXXX-X';
    break;

  case 'www.example.org':
    $config['google_analytics.settings']['account'] = 'UUA-XXXXXXXX-Y';
    break;

  default:
    $config['google_analytics.settings']['account'] = 'UA-XXXXXXXX-Z';
}