Dynadot

PHP: Ternary Operators

Spaceship Spaceship
Watch
Note this tutorial was written a while back, as such my coding habits have been changed a bit and some formatting it a bit out of date :)

This tutorial will explain the method known as "ternary operators" which you will see me especially using a lot. They are also present in javascript and a few other languages, but that's not the point of this tutorial. It's just a quicky and not that in depth but i hope you get something out of it.

Every found your self diving into endless reams of code just to set a simple variable??

e.g:

PHP:
<?php
if( $arraycount > 1 ) 
{
	$result = 'yes';
}
else
{
	$result = 'no';
}
?>

How stupid is that? So many lines of code for just 1 variable?

The Quick if!

It works like this:

function/string ( first condition ) ? "value if true" : "value if false";

So for the above code, we can do this:

PHP:
<?php	   
$result = ( $arraycount > 1 ) ? 'yes' : 'no';
?>

It does the exact same thing!!

Of course you can also do:

PHP:
<?php
echo  ( $arraycount > 1 ) ? 'yes' : 'no';
?>

And another example because im bored and theres nothing on TV.

PHP:
echo (eregi('msie', getenv('HTTP_USER_AGENT'))) ? 'Youre using IE!' : 'Youre not using IE!';


Anything really, its a good way of keeping order in your code and sparing your fingers. There are a few disadvantages to this technique, for starters it is rarely ever used within a tutorial as the conditional can be missed and since the technique is not widely used it is also not widely understood. The format of the conditional is also not great when debugging.

Any questions/comments, post below and when i get time i or someone else will reply.
Matt.
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
Thanks for explaning that, I'd seen similar syntax a while back and didn't exactly understand how it worked

Rep++ (I think) :)
 
0
•••
I use this all the time. Makes code a lot cleaner indeed.
Good call :)
 
0
•••
Thanks for the rep Lee :) Glad it helped.

Just be sure not to overuse it psalzmann :D
 
0
•••
sorrry ya i didnt understand thank you for ur tutorial
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back