Special Operators

The ternary operator and the execution operator work differently from those we have seen so far. The ternary operator is rarely used in PHP, thankfully, because it is really just a condensed conditional statement. Presumably it arose through someone needing to make his code occupy as little space as possible because it certainly does not make PHP code any easier to read!

The ternary operator works like this:

$age_description = ($age < 18) ? "child" : "adult";

Without explanation, that code is essentially meaningless; however, it expands into the following five lines of code:

$age_description = "adult";

The ternary operator is so named because it has three operands: a condition to check ($age < 18 in the previous code), a result if the condition is true ("child"), and a result if the condition is false ("adult"). Although we hope you never have to use the ternary operator, it is at least important to know how it works in case you stumble across it.

The other special operator is the execution operator, which is the backtick symbol, *. The position of the backtick key varies depending on your keyboard, but it is likely to be just to the left of the 1 key (above Tab). The execution operator executes the program inside the back ticks, returning any text the program outputs. For example:

That executes the ls program, passing in l (a lowercase L) to get the long format, and stores all its output in $i. You can make the command as long or as complex as you like, including piping to other programs. You can also use PHP variables inside the command.

0 0

Post a comment