Pantura Hosting

Pantura Hosting

Advertisment

Klasemen Sepakbola

Statistik Website

mod_mod_visitcounterVisitors Online14
mod_mod_visitcounterHits4780489
mod_mod_visitcounterToday899
mod_mod_visitcounterYesterday1266
mod_mod_visitcounterThis week6768
mod_mod_visitcounterThis month23404
mod_mod_visitcounterAll days1020455

Using the Ternary Operator in PHP

Rating: 4.3/10 (108 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