I read a lot of helpful info here when searching for answers to my programming questions. I just signed up because I want to ask a question about PHP variables that I am not able to find a concise answer on.
I want to check if a PHP variable has changed.
I have a form field that users type their city, state into. It gets stored in $_SESSION['location']
.
I also have a variable that stores country.
When the $country
variable changes, the city, state remain in the form field due to it being in session. This is an issue because obviously the city, state originally entered won't work for a different country that gets selected.
I need to be able to unset the $_SESSION['location']
each time the country variable changes so that the form field returns to empty. I'm not sure how to do this. But here is my code below with an attempt of trying to unset the session in my if statement.
// Country Selector
switch ($country) {
case "USA":
$example = "San Jose, CA or 94102";
$placeholder = "city, state, or zip";
break;
case "Canada":
$example = "Toronto, ON";
$placeholder = "city, state";
break;
case "India":
$example = "New Delhi, Delhi";
$placeholder = "city, state";
break;
default:
$example = "San Jose, CA or 94102";
$placeholder = "city, state, or zip";
}
// Location Search
$location = '';
$prev_country = $country;
if ($country == $prev_country) {
if (isset($_POST['location'])) {
$_SESSION['location'] = $location = ucwords($_POST['location']);
header('Location: '.($_SERVER['REQUEST_URI']));
} elseif (isset($_SESSION['location'])) {
$location = $_SESSION['location'];
}
} else {
unset($_SESSION['location']);
unset($_POST['location']);
$location = '';
}
UPDATE
I tried suggestions using if ($country == $_SESSION['country'])
but still getting same result as before in previous code.
// Location Search
$location = '';
$_SESSION['country'] = $country;
if ($country == $_SESSION['country']) {
if (isset($_POST['location'])) {
$_SESSION['location'] = $location = ucwords($_POST['location']);
header('Location: '.($_SERVER['REQUEST_URI']));
} elseif (isset($_SESSION['location'])) {
$location = $_SESSION['location'];
}
} else {
unset($_SESSION['location']);
unset($_POST['location']);
$location = '';
}