Declination of words in php \ javascript
The last notes
All English-language materials have been translated fully automatically using the Google service
Word declension in javascript
We will use a small javascript function for declension of numerical values. As arguments, it is passed a number and an array of word forms with different numerical values. The result can be used as intended.
function num2str (n, text_forms) {
n = Math.abs (n)% 100; var n1 = n% 10;
if (n> 10 && n <20) {return text_forms [2]; }
if (n1> 1 && n1 <5) {return text_forms [1]; }
if (n1 == 1) {return text_forms [0]; }
return text_forms [2];
}
The function is applied as follows:
$ ('# p1'). html ('1' + num2str (1, ['minute', 'minutes', 'minutes']));
$ ('# p2'). html ('2' + num2str (2, ['minute', 'minutes', 'minutes']));
$ ('# p3'). html ('5' + num2str (5, ['minute', 'minutes', 'minutes']));
Word declension in php
/ *
* $ num number, on which the form of the word will depend
* $ form_for_1 the first form of a word, for example Product
* $ form_for_2 second form of the word - Goods
* $ form_for_5 third plural form - Goods
* /
function true_wordform ($ num, $ form_for_1, $ form_for_2, $ form_for_5) {
$ num = abs ($ num)% 100; // take the number modulo and reset hundreds (divide by 100, and assign the remainder to the $ num variable)
$ num_x = $ num% 10; // reset tens and write to a new variable
if ($ num> 10 && $ num <20) // if the number belongs to the segment [11; 19]
return $ form_for_5;
if ($ num_x> 1 && $ num_x <5) // otherwise if the number ends in 2,3,4
return $ form_for_2;
if ($ num_x == 1) // otherwise if it ends in 1
return $ form_for_1;
return $ form_for_5;
}
Function application:
$ max_product = 5; // number, this variable can be set through some other function or taken from the base - it doesn't matter
echo $ max_product. ''. true_wordform ($ max_product, 'product', 'product', 'products'); // the result will be "5 products"
Materials used:
Comments