0

I have the next code inside PHP function:

$_SESSION['verified'] = true;
return true;

Can I replace it with:

return $_SESSION['verified'] = true;

If yes, will the value be assigned to $_SESSION['verified'] after function is terminated?

Acidon
  • 1,294
  • 4
  • 23
  • 44
  • 1
    Yes, yes you can. your two lines of code are the same result. The assignment will happen then the return. – Scuzzy Mar 01 '23 at 23:00
  • @KIKOSoftware Nope - researching theory atm and don't have environment set up. I searched on Google and here though before posting it first. – Acidon Mar 01 '23 at 23:02
  • 1
    Well, as Scuzzy already said: Yes, this will work. It's how expressions are evaluated, the return will be the last thing. – KIKO Software Mar 01 '23 at 23:04
  • @Scuzzy perfect thanks, couldn't find anything on assignment while returning. – Acidon Mar 01 '23 at 23:04
  • 1
    In these cases it's easier to simply try, than to study documentation. – KIKO Software Mar 01 '23 at 23:05
  • @KIKOSoftware hey, we've just created the documentation with this post together so its all good ;) – Acidon Mar 01 '23 at 23:10
  • In the future if you search for `PHP Sandbox` you can use one of the online environments. I usually use https://3v4l.org/ but there are a few options. This thread is useful, https://stackoverflow.com/questions/4616159/is-there-a-php-sandbox-something-like-jsfiddle-is-to-js – user3783243 Mar 01 '23 at 23:19

1 Answers1

1

In PHP, when you use an assignment expression like $_SESSION['verified'] = true, the value of true is assigned to the $_SESSION['verified'] variable, and the expression also evaluates to that value (true). By using the expression return $_SESSION['verified'] = true;, you are both assigning true to $_SESSION['verified'] and returning that same value. I hope this part make sence, Then because the assignment expression is evaluated first, $_SESSION['verified'] will be assigned the value true before the return statement is executed. Therefore, the value of $_SESSION['verified'] will also be true when the function returns true.

In summary, you can replace $_SESSION['verified'] = true; return true; with return $_SESSION['verified'] = true; to achieve the same result with less code, and the value of $_SESSION['verified'] will still be assigned as true before the function returns.

Ayb009
  • 220
  • 2
  • 11