Only an implementation alternative if you are using PHP 5.5 :
$html = [' (nenhum)', ' (1 item)', ' ('.$ni.' itens)'][($ni > 1) ? 2 : $ni];
I find it simpler that way. I do not like conditional double in ternary operator.
You can do the same before version 5.5 but it is not so simple (at least comparing with the version of the double ternary):
$textos = [' (nenhum)', ' (1 item)', ' ('.$ni.' itens)'];
$html = $textos[($ni > 1) ? 2 : $ni];
This still requires PHP 5.4. For previous versions:
$textos = array(' (nenhum)', ' (1 item)', ' ('.$ni.' itens)');
$html = $textos[($ni > 1) ? 2 : $ni];
With if
for those who prefer (becoming less and less advantageous):
$textos = array(' (nenhum)', ' (1 item)', ' ('.$ni.' itens)');
if($ni > 1) {
$html = $textos[2];
} else {
$html = $textos[$ni];
}
Finally taking advantage of other answers posted as I would in this situation:
function pluralization( $numItems = 0, $texts) {
if ($texts == NULL) {
$texts = array("(nenhum)", "(1 item)", "($numItems itens)");
}
return $texts[min($numItems, 2)];
}
echo pluralization(0);
echo pluralization(0);
echo pluralization(1);
echo pluralization(2);
echo pluralization(3);
$elementos = 4; // podia usar o letral direto mas no uso real vai fazer mais sentido com uma variável
echo pluralization($elementos, ["nada", "um elemento", "$elementos elementos"]);
See running on ideone . And in Coding Ground . Also put it in GitHub for future reference .