Given the following PHP code, how can I display the word problems if the number is greater than one and how can I display the word problem if the output of the variable is 1 or 0?
echo "$number problems";
Given the following PHP code, how can I display the word problems if the number is greater than one and how can I display the word problem if the output of the variable is 1 or 0?
echo "$number problems";
I would recommending an if-else check where the "condition" does a check against the value of $number
using some comparison operator.
https://www.w3schools.com/php/php_if_else.asp
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
You could also use a ternary https://davidwalsh.name/php-shorthand-if-else-ternary-operators
If you are going to be using this frequently, just make a pluralize function so you don’t repeat yourself:
function pluralize($count, $word) {
return $count . ‘ ‘ . $word . ($count!=1 ? ‘s’ : ‘’);
}
// usage:
echo pluralize($number, ‘problem’);
The magic is in the ternary operator: if the count does not equal one, add an ‘s’