Skip to content
Advertisement

How to get multiple values through session from a file which is running multiple times in PHP

I have a file which is run 2 to 3 times and there is a variable $student_name, and I want that variable to be available in another file. How to achieve it?

file 1.

$info[] = $student_name;
$_SESSION["student_name"] = $info;

file 2.

for($i = 0 ; $i < count($_SESSION['student_name']) ; $i++) {
   echo $_SESSION['student_name'][$i];
} 

but I am getting only the last assigned value.

Advertisement

Answer

If file 1 is executed 3 times, then $info will be re-created empty in that file each time – it does not persist between different script executions. So then $_SESSION["student_name"] will be overwritten with this new $info variable each time, which presumably only contains one entry.

But Session variables are persisted between executions, that’s the whole point of them! So instead, just check whether the session variable exists, and if it does, append $studentname directly to that existing array. If it doesn’t, create the array with the first name entry in it.

Something like this (in file 1):

if (isset($_SESSION["student_names"])) $_SESSION["student_name"][] = $student_name;
else $_SESSION["student_names"] = array($student_name);

(Note that I renamed the session key to student_names (plural) to be more meaningful, and reflect the fact it can contain multiple values.)

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement