Pantura Hosting

Pantura Hosting

Advertisment

Klasemen Sepakbola

Statistik Website

mod_mod_visitcounterVisitors Online24
mod_mod_visitcounterHits4297103
mod_mod_visitcounterToday2314
mod_mod_visitcounterYesterday2645
mod_mod_visitcounterThis week14408
mod_mod_visitcounterThis month49224
mod_mod_visitcounterAll days933186

Using the Ternary Operator in PHP

Rating: 4.3/10 (106 votes cast)

It took me a while to actually figure out the name of this type of operator since trying to search “PHP” and “question mark” didn’t really result in anything useful. You’ve probably seen the ternary operator used multiple times in code and just never really understood what it was and how it worked. All it is, is a simpler alternative to setting a variable using an if-else conditional statement.

We can take the following if-else conditional statement:

if ( 'on' == $value )
$check = 'It is on';
else
$check = 'It is off';

And replace it with a ternary operator to get this:

// The parentheses around the conditional statement are not required
// I just like to use them as a visual guide
$check = ( 'on' == $value ) ? 'It is on' : 'It is off';

That breaks down to:

$variable =( condition)? true:false;

If the value of our $value variable equals ‘on’, then our $check variable will equal to ‘It is on’. Otherwise, it will equal to ‘It is off’.

Once you grasp how the ternary operator works it is a great tool to use to trim down your code and simplify your conditional statements.

Read more about the ternary operator on the PHP website.



Berita Terkait : Snippet