isset PHP isset($_GET['something']) ? $_GET['something'] : ''

前端 未结 8 1431
清酒与你
清酒与你 2020-12-13 04:02

I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it. I am looking at php.net isset code, and I see

相关标签:
8条回答
  • 2020-12-13 04:55

    That's called a ternary operator and it's mainly used in place of an if-else statement.

    In the example you gave it can be used to retrieve a value from an array given isset returns true

    isset($_GET['something']) ? $_GET['something'] : ''
    

    is equivalent to

    if (isset($_GET['something'])) {
      $_GET['something'];
    } else {
      '';
    }
    

    Of course it's not much use unless you assign it to something, and possibly even assign a default value for a user submitted value.

    $username = isset($_GET['username']) ? $_GET['username'] : 'anonymous'
    
    0 讨论(0)
  • 2020-12-13 05:01

    It's commonly referred to as 'shorthand' or the Ternary Operator.

    $test = isset($_GET['something']) ? $_GET['something'] : '';
    

    means

    if(isset($_GET['something'])) {
        $test = $_GET['something'];
    } else {
        $test = '';
    }
    

    To break it down:

    $test = ... // assign variable
    isset(...) // test
    ? ... // if test is true, do ... (equivalent to if)
    : ... // otherwise... (equivalent to else)
    

    Or...

    // test --v
    if(isset(...)) { // if test is true, do ... (equivalent to ?)
        $test = // assign variable
    } else { // otherwise... (equivalent to :)
    
    0 讨论(0)
提交回复
热议问题