Search code examples
phplanguage-featuresternary-operatorlanguage-construct

Does there exist a shorter if statement in PHP?


Is it possible to rewrite this to be shorter somehow?

if (isset($_POST['pic_action'])){
  $pic_action=$_POST['pic_action'];
}
else { 
  $pic_action=0;
}

I have seen it somewhere but forgot... :/

BTW, please explain your code also if you like!

Thanks


Solution

  • You could use the conditional operator ?::

    $pic_action = isset($_POST['pic_action']) ? $_POST['pic_action'] : 0;
    

    The conditional operator expression expr1 ? expr2 : expr3 evaluates to the return value of expr2 if the evaluated return value of expr1 is true; otherwise the expression evaluates to the evaluated return value of expr3. So if isset($_POST['pic_action']) evaluates to true, the whole expression evaluates to the evaluated value of $_POST['pic_action'] and to the evaluated value of 0 otherwise.

    So in short: if isset($_POST['pic_action']) is true, $pic_action will hold the value of $_POST['pic_action'] and 0 otherwise.