Form submission: PHP S_SESSION statements within a foreach loop

Let’s suppose I have the following PHP code which attempts to read from an array called $arr which takes on the values {fullname, studentnumber, email}. Upon submission of my HTML form, this PHP code will execute the foreach loop, and store the values posted to the page in the $_SESSION array.

foreach($arr as $field):
    $_SESSION[$field] = $_POST[$field];
endforeach;

The above code doesn’t work as intended. If I were to replace the above code block with the code below, the values in the fields on my page get stored correctly in the $_SESSION array.

$_SESSION[fullname] = $_POST[fullname];
$_SESSION[studentnumber] = $_POST[studentnumber];
$_SESSION[email] = $_POST[email];

How do I accomplish this, in an efficient and expandable way? I don’t want to have to write new $_SESSION statements every time I add a new field to my form.

EDIT: // The first block of code actually works as intended. There was a typo originally!

Leave a Comment