Reputation: 111
I'm working on member edit page, so for each html input I use sessions to echo values like:
value="<?php echo htmlspecialchars($_SESSION['username']));?>
value="<?php echo htmlspecialchars($_SESSION['email']));?>
etc... once member edits profile, i use query again to fetch new updated $results.
This is the old way i did to unset/set new sessions:
unset($_SESSION['user']);
unset($_SESSION['email']);
unset($_SESSION['first_name']);
unset($_SESSION['last_name']);
unset($_SESSION['birth_date']);
unset($_SESSION['about_me']);
unset($_SESSION['gender']);
unset($_SESSION['last_activity']);
unset($_SESSION['image_avatar']);
$_SESSION['user'] = $result['user'];
$_SESSION['email'] = $result['email'];
$_SESSION['first_name'] = $result['first_name'];
$_SESSION['last_name'] = $result['last_name'];
$_SESSION['birth_date'] = $result['birth_date'];
$_SESSION['about_me'] = $result['about_me'];
$_SESSION['gender'] = $result['gender'];
$_SESSION['last_activity'] = $result['last_activity'];
$_SESSION['image_avatar'] = $result['image_avatar'];
but i wanted less code lines and tried making foreach like this:
foreach($result as $key => $value) {
unset($_SESSION[$key]);
}
foreach($result as $key => $value) {
$_SESSION[$key] = $value;
}
using foreach works fine, but my only questions is, if this right way to do it?
Upvotes: 0
Views: 191
Reputation: 94662
The only improvement I can think of is to do it all in one foreach and there is no need to unset a value you are going to replace anyway
foreach($result as $key => $value) {
// not necessary if you are going to replace the value anyway
//unset($_SESSION[$key]);
$_SESSION[$key] = $value;
}
Upvotes: 1