rwhite35 Posted March 1, 2015 Share Posted March 1, 2015 I thought I would add this topic since I'm in need of an answer and don't see much ternary used in code examples. Using a ternary operator to assign a file path to a local variable. The path string is conditional, depending on which page id was passed to the script. Once the $_GET variable is evaluated, I like to unset these variables as a personal "memory maintenance" preference (even though garbage collection is automatic). Would prefer to only call unset( ) if $_GET[pageid] is set. The second code block makes the issue clearer. Here is the code I've tried. It generates an error. $fpath = (unset(isset($_GET['pageid']))) ? "path/to/file2.txt" : "path/to/file1.txt"; //error Parse error: syntax error, unexpected 'unset' (T_UNSET) /* for comparison purpose, does same thing as above * but works as expected because ifelse construct * allows for stacking functions within a code block. * where ternary seems to have a problem with unset(). */ if (isset($_GET['pageid'])) { $fpath = "path/to/file2.txt"; unset($_GET['pageid']); } else { $fpath = "path/to/file1.txt"; } Quote Link to comment https://forums.phpfreaks.com/topic/294985-stacking-function-within-ternary-initial-expression/ Share on other sites More sharing options...
Barand Posted March 1, 2015 Share Posted March 1, 2015 Move the "unset()" out out of the statement. It isn't trying to unset the GET variable, it is trying to unset the boolean result return by the isset() function. Quote Link to comment https://forums.phpfreaks.com/topic/294985-stacking-function-within-ternary-initial-expression/#findComment-1507143 Share on other sites More sharing options...
Solution mac_gyver Posted March 1, 2015 Solution Share Posted March 1, 2015 this kind of micro optimization is counter productive. the amount of memory the bytecode for the unset statement and the variable reference operand it contains, is the same or more than the amount of memory you would be freeing up. on top of that, you have wasted the processing time needed to parse, tokenize, and then run the extra code. Quote Link to comment https://forums.phpfreaks.com/topic/294985-stacking-function-within-ternary-initial-expression/#findComment-1507151 Share on other sites More sharing options...
rwhite35 Posted March 1, 2015 Author Share Posted March 1, 2015 @mac_gyver, excellent point. I hadn't thought about that. @Barand, for the sake of completeness, I'll give that try. Thanks you both. Quote Link to comment https://forums.phpfreaks.com/topic/294985-stacking-function-within-ternary-initial-expression/#findComment-1507155 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.