achur00
achur00

Reputation: 9

Problem using PHP null coalescing together with ternary operator to reset a Session

I am trying to reset the Session with the below code:

<?= 
$_SESSION['pettySuccess']??''; 
(($_SESSION['pettySuccess']??'')=='') ?'': unset($_SESSION['pettySuccess']); 
?>

the idea behind my code is for the pettySuccess session to reset the session when it doesn't evaluate as ' ' but here I am getting a syntax error. The weird thing is when I changed the unset() method to session_unset(), I dont have a syntax error anymore, the error I got now was that 'the session_unset() does not accept any attributes' and my intention was never to reset all my session variables.

Upvotes: -1

Views: 105

Answers (2)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146588

I don't know what your business logic is, but I suspect all you need is:

unset($_SESSION['pettySuccess']);

unset() is a language construct so it's able to detect and ignore missing variables (something that regular functions cannot do), and it actually does (yes, it's unfortunately not documented).

Upvotes: 0

noah1400
noah1400

Reputation: 1509

unset() is a statement and not a function, so it cannot be used directly within a ternary operator. You can use the following code:

if (isset($_SESSION['pettySuccess']) && $_SESSION['pettySuccess'] !== '') {
    unset($_SESSION['pettySuccess']);
}

Upvotes: 1

Related Questions