Skip to main content

How to pluralize sentences in Drupal 8

Posted on March 27, 2020


Here is a way to save a few lines of code when pluralizing sentences

$count = 1;
$message_one = \Drupal::translation()->formatPlural($count, "$count node was updated.", "$count nodes were updated.");
echo $message_one // "1 node was updated."

$count = 8;
$message_two = \Drupal::translation()->formatPlural($count, "$count node was updated.", "$count nodes were updated.");
echo $message_two // "8 nodes were updated."

Reference: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21StringTranslation%21TranslationInterface.php/function/TranslationInterface%3A%3AformatPlural/8.8.x