ngettext

(PHP 4 >= 4.2.0, PHP 5)

ngettext -- Plural version of gettext

Description

string ngettext ( string msgid1, string msgid2, int n )

ngettext() returns correct plural form of message identified by msgid1 and msgid2 for count n. Some languages have more than one form for plural messages dependent on the count.

例子 1. ngettext() example

<?php

setlocale
(LC_ALL, 'cs_CZ');
printf(ngettext("%d window", "%d windows", 1), 1); // 1 okno
printf(ngettext("%d window", "%d windows", 2), 2); // 2 okna
printf(ngettext("%d window", "%d windows", 5), 5); // 5 oken

?>


add a note add a note User Contributed Notes
nikolai dot zujev at gmail dot com
22-Mar-2006 05:36
This is an implementation for a word ending in russian lang. Also as I know polish and similar langs use same rules:

<?php
/**
 * Returns:
 *  0, if $n == 1, 21, 31, 41, ...
 *  1, if $n == 2..4, 22..24, 32..34, ...
 *  2, if $n == 5..20, 25..30, 35..40, ...
 */
function plural( $n )
{
   if (
$n % 10 == 1 && $n % 100 != 11 )
   {
       return
0;
   }

   if (
$n % 10 >= 2 && $n % 10 <= 4 && ( $n % 100 < 10 || $n % 100 >= 20 ) )
   {
       return
1;
   }

   return
2;
}

// usage
for ( $i = 0; $i < 100; $i++ )
{
  
$x = plural( $i );

  
printf(
      
"%d %s<br/>\n", $i,
         (
0 == $x ? '' : ( 1 == $x ? '' : '' ) )
   );
}
?>

Output:
0
1
2
3
4
5
6
7
8
9
10
...

Also here is short version:

<?php
$n
= 17;
print (
$n%10==1 && $n%100!=11 ? 0 : ($n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20) ? 1 : 2));
?>

output: 2
mike-php at emerge2 dot com
04-Nov-2004 04:53
Section 10.2.5 in the GNU gettext manual explains the ngettext function:

http://www.gnu.org/software/gettext/manual/

(Sorry, but the Add Note function prevents me from including a long URL which points right to that section of the manual.)