You get a bonus - 1 coin for daily activity. Now you have 1 coin

Programmatic noun declension by number in PHP

Practice




Programmatic noun declension by number in PHP

function RusSklonenie($n, $null, $one, $variant1, $variant2)
{
$nmod10 = $n % 10;
$nmod100 = $n % 100;
$str;
if (!$n)
{
$str = $null;
} elseif (($n == 1) || ($nmod10 == 1 && $nmod100 != 11))
{
$str = $one;

} elseif (($nmod10 > 1) && ($nmod10 < 5) && ($nmod100 != 12 && $nmod100 != 13 && $nmod100 != 14))
{
$str = $variant1;
} else
{
$str = $variant2;
}
return $str;
}

RusSklonenie($n, "нет строк", "$n строка", "$n строки", "$n строк");

The algorithm for declining nouns by number is simple. There can be four cases in total. As an example, let's decline the word «комментарий» ("comment") by number:
Case 1. The number equals zero. This case can be handled to taste, for example: «ни одного комментария» ("not a single comment"), «нет комментариев» ("no comments"), etc. But under no circumstances should you write «0 комментариев» ("0 comments"), since that form is not used in normal human speech.
Case 2. The number equals one, or the remainder of dividing by 10 equals one, but the number is not 11. In this case, our example takes the following form: «n комментарий» ("n comment"), where n is the number of comments.
Case 3. The remainder of dividing the number by 10 is greater than one but less than five, and the remainder of dividing by 100 is not 12, 13, or 14. Numbers such as 22, 23, 54, 2, 3, 173, etc. fall into this range. The exceptions to this case are the numbers 12, 13, 14. Our example becomes: «n комментария» ("n comments").
Case 4. All other numbers. All remaining numbers fall into a separate category. The example becomes: «n комментариев» ("n comments").

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Running server side scripts using PHP as an example (LAMP)"

Terms: Running server side scripts using PHP as an example (LAMP)