Skip to main content
4 of 4
Add a simplified version that works on modern PHP versions.

You can do it with this code.

// Language to search.
$find = 'French';

// Getting all the available languages.
$languages = \Drupal::service('language_manager')->getStandardLanguageList();

$key = key(array_filter($languages, function ($array) use ($find) {
  if (array_search($find, $array) === FALSE) {
    return FALSE;
  }
  return TRUE;
}));

// If you have the devel module installed you can use the dpm function.
dpm($key);

Or, if you are on PHP 7.4+:

// Language to search.
$find = 'French';

$languages = \Drupal::service('language_manager')::getStandardLanguageList();
$langcode = key(array_filter($languages, fn ($lang) => in_array($find, $lang)));
Adrian Cid Almaguer
  • 18.5k
  • 14
  • 79
  • 133