Search code examples
phpfunctionreturnglobal-variables

PHP function: Can it return a global variable while simultaneously assigning a value to it?


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?


Solution

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