2

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";
Jacob K.
  • 115
  • 2
  • 16

3 Answers3

0

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

Patrick Fay
  • 552
  • 3
  • 15
0

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’

Tim Morton
  • 2,614
  • 1
  • 15
  • 23
  • Oops sorry this one does not say “0 problem” as you requested, it says “0 problems” per normal usage. To have the former output, you just need to change the logic of the ternary comparison: $count>1 – Tim Morton Jun 10 '19 at 04:10
0
$var = 1;
if($var > 1){
echo "Greater";
} else {
echo "Less";
}
kishan
  • 16
  • 3