undefined php variable on page load

Soldato
Joined
7 Jan 2007
Posts
10,607
Location
Sussex, UK
Last problem I have is that when I load my formpage.php it errors with undefined variable in the for each of the cases in the switch.

I suspect it's something to do wtih the isset submit stuff at the top, because until someone presses submit, then the variable $education is not defined.. but I am unsure how to fix it... Can anyone help me?

PHP:
<?php
if (isset($_POST['submit'])) {
  if (isset($_POST["Education"])){
	$education = $_POST["Education"];
	}
}

?>

<html> 
<head> 
<title>Personal INFO</title> 
</head> 
<body> 
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
Select your level of education:<br /> 
<select name="Education"> 
<option value="Default"></option> 
<option value="PrimarySchool">Primary School</option> 
<option value="MiddleSchool">Middle School</option> 
<option value="HighSchool">High School</option></select><br /> 
<input type="submit" value="submit" name="submit"> 
</form>

<?php

switch ($education){
	case "Default":
		echo "Display stuff";
		break;
    case "PrimarySchool":
		echo "Primary School";
		break;
    case "MiddleSchool":
        echo "Middle School";
        break;    
    case "HighSchool":
        echo "High School";
        break;   
        }

?> 

</body> 
</html>
 
Just define $education outside of the conditional statements at the top. Set it to null or default and then will always have it set for the switch below.

If you set it to null or anything but one of the strings you are looking for you can just use the default for the last one which will pick up the scraps as such.
 
ah yes, that works, i tried that on my mamp, but it came up with an undefined index error, just shoved the same file on my web hosting and no error.

I must have some super sensitive error reporting on my mamp.

am I ok to ignore?
 
Just put $education = ''; at the top above the first if. Or wrap your switch in:

Code:
if(isset($education) && $education != '') 
{
  switch()
}

also in a switch statement, you can assign a default with

Code:
switch($education)
{
  case 1: $something = 'something'; break;
  default: $something = 'nothing'; 
}

Undefined index just means a variable that isn't set. You only set $education inside your if statement, but it's declared in that switch even without $_POST.
 
Last edited:
Back
Top Bottom