cloudll Posted January 31, 2016 Share Posted January 31, 2016 Hey, I have only recently learnt about using shorthand. I have managed to convert most of my simple if else's and isset checks to shorthand but am struggeling with a few. Could someone show me how I would change this to shorthand, when it has two variables in the else. if (isset($_SESSION['posY'])) { $posY = $_SESSION["posY"]; } else { $posY = 50; $_SESSION["posY"] = 50; } Thanks Quote Link to comment Share on other sites More sharing options...
Barand Posted January 31, 2016 Share Posted January 31, 2016 see http://pitmanshorthand.homestead.com/BasicsofPitman.html 1 Quote Link to comment Share on other sites More sharing options...
Solution requinix Posted January 31, 2016 Solution Share Posted January 31, 2016 If I may translate that, What do you mean by "shorthand"? If you mean the ternary operator ? : then the answer is, While possible, in this case you shouldn't. That's more appropriate if you have "if ($condition) $var = $value; else $var = $other_value;". Your if has two statements in that else so it's really just better to leave it as is. And this is coming from someone who generally does use shorthand. Quote Link to comment Share on other sites More sharing options...
cloudll Posted January 31, 2016 Author Share Posted January 31, 2016 Ah yes, I did mean ternary operator. Ah ok that makes sense. Thank you. Quote Link to comment Share on other sites More sharing options...
mac_gyver Posted January 31, 2016 Share Posted January 31, 2016 // set a default value if not already set - if(!isset($_SESSION['posY'])){ $_SESSION["posY"] = 50; } // and if you really, really, really are creating more variables holding values that you already have variables for (what's wrong with using $_SESSION["posY"] ?) - $posY = $_SESSION["posY"]; Quote Link to comment Share on other sites More sharing options...
Jacques1 Posted January 31, 2016 Share Posted January 31, 2016 PHP 7 has a nice null coalescing operator for exactly this purpose: $_SESSION["posY"] = $_SESSION["posY"] ?? 50; If $_SESSION["posY"] is already set, it's left alone, otherwise it's set to the default value 50. JavaScript and Ruby have the same thing, so it's a fairly common concept (PHP is just a bit late again). 1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.