Question:
Hello, we gave you a PHP problem
Write an array with numbers from 1 to 30 [1, 2, 3 ….] and a function that does the following goes through the array and adds the phrase "new comments" to each number, and these words are declined in accordance with their number and makes as a result array 1 new comment 2 new comments and so on and display in html in element
I ask you to help with examples of solutions , I'm a beginner in PHP, I studied the theory not badly, but I have been sitting for several days and it has not yet come to use in this example.
Answer:
There is an article on plurals. There are collected plural algorithms for many countries. Algorithms are presented in the form of formulas. There is no need to reinvent the wheel. We use formulas in mathematics.
In this case, we take the Russian language: nplurals=3
That is, for the Russian language there are three plural forms:
1) When there is only one element. For example : 1 new comment
2) When there are more than two elements, but less than five. For example : 3 comments, 4 comments
3) When the elements are greater than or equal to five. For example : 5 new comments, 6 new comments
Now let's move on to the implementation. I made the conditions more readable:
$numbers = ['1', '2', '3', '4', '5']; function plural($number) { if ($number % 10 == 1 && $number % 100 != 11) { return $number . ' новый комментарий'; } else { if ($number % 10 >= 2 && $number % 10 <= 4 && ($number % 100 < 10 || $number % 100 >= 20)) { return ($number . ' новых комментария'); } else { return ($number . ' новых комментариев'); } } } foreach ($numbers as $number) { echo plural($number); echo '<br>'; }