Question about ? and : when used with isset

I need help with the follow code:

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

I understand basically what it is saying, to create a session variable for ‘name’ if is is already set, and if it is not already set then let it be equal to null. But what exactly does the ? and the : do in this code?

Thank you

You need to read more on ternary operator.

They do a better job of explaining this.

1 Like

SitePoint is more than only a forum, there are articles too.

It can also be used for more than two options by adding another ternary operator as the ELSE of the first. Say you have the option of showing First Name, User Name or No Name. More than likely these variables WOULD be set from a DB query and thus I would use !empty() but I’m using isset() in this example.

$name1 = "First Name";
$name2 = "User Name";
$name = (isset($name1) ? $name1 : (isset($name2) ? $name2 : "no name")); 

Anyway, just pointing that out.

For those coming to PHP from another language, a very important heads up about PHP’s ternary operator - it’s left associative and as a result broken and can’t be chained!!

Try this:

 // Set sessions 
   $_SESSION = array(); // clear previous results

// DRY (Don't Repeat Yourself)
   $xmas = 'MERRY_CHRISTMAS';
   $year = 'HAPPY_NEW_YEAR';
   $folk = ' to all staff and members at SitePoint';

// Maybe Set Default
   $_SESSION[$xmas] = isset( $_SESSION[$xmas] ) ?: 'Merry Christmas' .$folk;
   $_SESSION[$year] = isset( $_SESSION[$year] ) ?: 'Best wishes' .$folk;

// Test Results
   echo $xmas .' ==> ' .$_SESSION['MERRY_CHRISTMAS'];
   echo '<br />';
   echo $year .' ==> ' .$_SESSION['HAPPY_NEW_YEAR'];

// Free memory

// Output
   MERRY_CHRISTMAS ==> Merry Christmas to all staff and members at SitePoint
   HAPPY_NEW_YEAR ==> Best wishes to all staff and members at SitePoint

This is a short way to write:

if (isset($_SESSION['name']){  // The expression before the question mark
  // between the question mark and the colons
  $_SESSION['name'] = $_SESSION['name'];  
} else {
  // after the colons
  $_SESSION['name'] = $_SESSION['name'];  

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