- Impact
- 89
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:
How stupid is that? So many lines of code for just 1 variable?
The Quick if!
It works like this:
So for the above code, we can do this:
It does the exact same thing!!
Of course you can also do:
And another example because im bored and theres nothing on TV.
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.
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.