-1

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.

8
  • Unset is not a function and it doesn't return anything, so it cant be used as value for ternary operator. Also you are using ternary operator in a bad way, because you are not assigning nothing. You are also using a loose comparison so the unset will be executed also for valuse as NULL, 0 , false, etc. Try: if ($_SESSION['pettySuccess'] !== '') unset($_SESSION['pettySuccess']); Commented Nov 12, 2023 at 19:54
  • I think you might need to edit your comment a bit so I can understand all your points, but with I was able to pick up I figured what was wrong and it is about the unset() not being usable as a value in ternary operation, I still don't understand why session_unset() works just fine and unset() doesn't. Commented Nov 12, 2023 at 21:54
  • @okunadeyusuf session_unset() returns a boolean value and it can be evaluated. To be more precise, unset() regardless of whether it is considered a function or not, returns void, like var_dump() or echo and the void value can't be used in expressions. Commented Nov 12, 2023 at 23:54
  • oh, I understand now, if I were to stick with my code I could use something like this then : <?= $_SESSION['pettySuccess']??''; (($_SESSION['pettySuccess']??'') !=='') ?$_SESSION['pettySuccess']='':'' ; ?> Commented Nov 13, 2023 at 4:52
  • $_SESSION['pettySuccess']??''; by itself doesn't accomplish anything, you aren't storing the generated value anywhere. Commented Nov 14, 2023 at 7:09

2 Answers 2

1

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']);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.