Created
May 6, 2025 05:22
-
-
Save AkostDev/dd90fd50e8bee71545f15f7ce27feb17 to your computer and use it in GitHub Desktop.
PHP-функция, которая автоматически подбирает правильное склонение слова в зависимости от указанного числа. Полезна для отображения товаров, комментариев, просмотров и любых элементов интерфейса, где нужно грамотно согласовать число и слово.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Склонение слова после числа | |
* | |
* @param int|string $n - число | |
* @param array $after - массив слов в различных падежах, напр. ['товар', 'товара', 'товаров'] | |
* @param bool $showN - показывать число в начале | |
* @param string $wrapper - обернуть слово в контейнер | |
* @return string | |
*/ | |
function pluralForm(int|string $n, array $after, bool $showN = true, string $wrapper = 'span'): string | |
{ | |
$n = intval($n); | |
$cases = [2, 0, 1, 1, 1, 2]; | |
$value = $after[($n % 100 > 4 && $n % 100 < 20) ? 2 : $cases[min($n % 10, 5)]]; | |
return ($showN ? $n : '') . (strlen($wrapper) ? "<$wrapper>" . ($showN ? ' ' : '') . "$value</$wrapper>" : $value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment