...

View Full Version : Resolved If/else improvement



[vengeance]
09-07-2009, 11:03 AM
Hey guys.

I know this following code can be improved - but how? I've seen something along with <if blabla> ? <do this> : <or do this>

This is my code.


<?php
$start = 2009;
if(date("Y") == $start){ $copy = $start; }else{ $copy = $start." - ".date("Y"); }
echo $copy;
?>


Thanks

Fou-Lu
09-07-2009, 01:02 PM
?: is called the ternary operator:

I'll add an explanation in: (condition) ? (true expression) : (false expression). In PHP5.3 I think its introduced, you can shortcut to just false using (condition)?:(false expression).



$copy = (date('Y') == $start) ? $start : $start . ' - ' . date('Y');

You may need to do some error checking (or embed more ternaries if you want) to handle if the $start > date('Y'), otherwise you could have '2012 - 2009' for example.

[vengeance]
09-07-2009, 02:19 PM
Thanks a lot, just what I was looking for. I recall doing something like your code earlier, but it just didn't work, lol.



You may need to do some error checking (or embed more ternaries if you want) to handle if the $start > date('Y'), otherwise you could have '2012 - 2009' for example.

That won't be necessary at this point, I'm just using this for a simple copyright message.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum