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 4 of 4
  1. #1
    Regular Coder
    Join Date
    Apr 2004
    Posts
    684
    Thanks
    24
    Thanked 1 Time in 1 Post

    Usage of '?' & ':' in PHP....

    Hey guys.... kind of a dumb question, been coding PHP for over 3 years now & for some reason never come across finding out what these mean....

    See the below code..

    PHP Code:
    $bla = isset($_POST['blah']) ?  $_POST['blah'] : false;

    echo 
    '<select name="blah">';

    echo 
    '<option value="opt_1" '$bla == 'opt_1' ?  'selected="selected"' '' .'>1</option>';
    echo 
    '<option value="opt_2" '$bla == 'opt_2' ?  'selected="selected"' '' .'>2</option>';
    echo 
    '<option value="opt_3" '$bla == 'opt_3' ?  'selected="selected"' '' .'>3</option>';

    echo 
    '</select>'
    What exactly is the use of the '?' & ':' in the above code?

    Thanks guys!

  • #2
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    It's called the ternary operator. It's basically a shorthand if/else.

  • #3
    Regular Coder
    Join Date
    Apr 2004
    Posts
    684
    Thanks
    24
    Thanked 1 Time in 1 Post
    Great..... thanks for that!

  • #4
    New Coder
    Join Date
    Mar 2008
    Location
    Lakeland, FL
    Posts
    39
    Thanks
    1
    Thanked 3 Times in 3 Posts
    I LOVE ternary operators :P Makes for much cleaner code when you don't really need to do anything but switch a variable around. It kind of amazes me that you've never seen it before. Maybe just haven't looked at any of my code I guess :P If there where a thing such as a "ternary operator whore" I'd be one


  •  

    Posting Permissions

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