Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Aug 2009
    Posts
    131
    Thanks
    28
    Thanked 7 Times in 7 Posts

    If/else improvement

    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 Code:
    <?php
    $start 
    2009;
    if(
    date("Y") == $start){ $copy $start; }else{ $copy $start." - ".date("Y"); }
    echo 
    $copy;
    ?>
    Thanks
    Last edited by [vengeance]; 09-07-2009 at 01:20 PM.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    ?: is called the ternary operator:
    Edit:
    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).

    PHP Code:
    $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.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    [vengeance] (09-07-2009)

  • #3
    Regular Coder
    Join Date
    Aug 2009
    Posts
    131
    Thanks
    28
    Thanked 7 Times in 7 Posts
    Thanks a lot, just what I was looking for. I recall doing something like your code earlier, but it just didn't work, lol.

    Quote Originally Posted by Fou-Lu View Post
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •