Jump to content

Stacking function within ternary initial expression


rwhite35
Go to solution Solved by mac_gyver,

Recommended Posts

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";
}
Link to comment
Share on other sites

  • Solution

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.