PHP: Use the ternary operator in PHP

A good program is sometimes equalized with few lines of code. But how do we program this way? One step is using the ternary operator...

What is it?

Ternary means 3. But nearly every operator you know is binary.

Some binary operator examples:

$a = $b + $c;
$a = $b - $c;
$a = $b % $c;
$a = $b * $c;

As you can see, +,-,% and * are binary operators because they need 2 variables for their action. But the ternary operator has one variable more!

How to use it?

The ternary operator has 3 "variables" and looks like this:

$result = $when ? $then : $else;

We can also write this in a normal if then else code:

if($when)
  $result = $then;
else
  $result = $else;

Example

Here a real life example i used in my code.
If i want to initialize a variable correct, this code is fast and tiny:

$iterations_max = (defined('ITERATIONS_MAX')) ? ITERATIONS_MAX : 10 ;

The if else version looks like this:

if ((defined('ITERATIONS_MAX')))
  $iterations_max = ITERATIONS_MAX;
else
  $iterations_max = 10;

Documentation

Hope you understood the usage of the ternary operator and might use it in your future code.

The documentation for this operator can be found here:
http://php.net/ternary

Related posts:


 
 
 

Die Kommentarfunktion zu diesem Beitrag wurde deaktiviert.