A question about session variables

Which is considered a cleaner way of coding, to define a session variable at the top of a page like this:

$_SESSION['sponsorID'] 	= isset($_SESSION['sponsorID']) ? $_SESSION['sponsorID'] : null; 

Or by using isset every time an IF statement is used, like this:

if (isset($_SESSION['sponsorID']) && isset($_SESSION['sponsorSubscription']) == "Gold") {  }

I assume it’s best to use my first example, but just wanted to verify. I’m cleaning up my code to get rid of notices dealing with undefined indexes and undefined variables.

Thank you.

I personally like doing it this way, for I figure you already have it in SESSION you might as well save some unnessary typing. :wink:

$sponsorId = isset($_SESSION['sponsorID']) ? $_SESSION['sponsorID'] : null;
1 Like

I’ll add my vote to Pepster’s way. Definitely I don’t want to use isset in every if statement!

Like @Pepster I prefer declaring all the session variables at the top of the page. It is easier to debug because the layout is cleaner:

$sponsorId   = isset( $_SESSION['sponsorId'] ) ?:  $_SESSION['sponsorId'] : NULL;
$sponsorSub  = isset( $_SESSION['sponsorSubscription'] ) ? $_SESSION['sponsorSubscription'] : NULL;

if ( $sponsorId && 'Gold' === $sponsorSub ) { // Did you notice the treble equal signs?
  echo '<pre>'; print_r($_SESSION); echo '</pre>';

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.