Variable text in exercises

Learn how to use PHP ternary operators to write variable text.

Updated over a week ago

Suppose you want to write the following sentence in the solution text of an exercise with random variables:

Anne should buy $a rolls of masking tape to paint her windows.

However, the variable $a can also be equal to one, in which case the sentence should be:

Anne should buy $a roll of masking tape to paint her windows.

The choice of the word roll/rolls depends on the value of variable $a. We could make a variable, for instance, $word, that contains the string “roll” or “rolls” depending on the value of $a. However, there is a better way to solve this problem, namely using PHP ternary operators.

These ternary operators work as follows:

~ evaluation ? ” text when evaluation is true ” : ” text when evaluation is false ” ~

The way this would work in the example above is:

Anne should buy $a ~$a>1?”rolls”:”roll”~ of masking tape to paint her windows.

If $a>1, then the evaluation is true, so the code between ~~ is replaced by the word “rolls”. If $a=1, then the evaluation is false, so the code between ~~ is replaced by the word “roll”. Alternatively, we could write:

Anne should buy $a roll~$a>1?”s”:””~ of masking tape to paint her windows.

It is also possible to use PHP ternary operators in variables. For example, variable $d returns 4 if $c=1 and it is empty when $c has a different value:

Did this answer your question?