Avatar of LB1234
LB1234
 asked on

Need help understanding how these nested PHP "if" and "else" statements relate to one another.

The following code works, but I'd like to improve my understanding of the if and else statements.  How do the first and second else statement know which if they're related to?

Does the first else statement pertain to the if statement directly above it?  I know the second else statement relates to the very first IF statement but I don't understand why it's not relating to any of the other IF statements instead?

Thanks.

<?php
      $errors = array();  
		
		if(isset($_POST["submit"])) {
	  	$first_name = $_POST["first_name"];
	  	$last_name = $_POST["last_name"];
	  	$user_name = $first_name . "_" . $last_name;
	  	$access_level = $_POST["access_level"];
		$department = $_POST["department"];
		$password = $_POST["password"];
	  	$password2 = $_POST["password2"];
		 	
		 if ($password !== $password2) {
			$errors[] = "Passwords do not match, please re-enter";  
		 if (empty($password)) {
			 $errors[] = "Password is empty, please enter a password";
		 }
		 
		  } else {
			$query = "INSERT INTO users (first_name, last_name, user_name,  department, password, password2, access_level) VALUES (";
			$query .= "'{$first_name}', '{$last_name}', '{$user_name}',  '{$department}', '{$password}', '{$password2}', '{$access_level}')";
			$result = mysqli_query($connection, $query);
			mysqli_close($connection);
			redirect_to("account_created.php");
		  }
	} else {
  
	  	$first_name = "";
	  	$last_name = "";
	  	$user_name = "";
	  	$access_level = "";
		$department = "";
		$password = "";
	  	$password2 = "";
	  	$message = "Please log in";
	}



?>

Open in new window

PHP

Avatar of undefined
Last Comment
Ray Paseur

8/22/2022 - Mon
Gary

First IF checks if the FORM has been submitted by checking if the SUBMIT value exists.
Second IF checks if the passwords match.  It then has a further IF to check if the password is empty (if so give a different error message)

If the form has been submitted and the passwords match and the passwords are not empty then add to database.

if(isset($_POST["submit"])) {
	// The form has been submitted
	if ($password !== $password2) {
		// If the passwords don't match set the error message

		if (empty($password)) {
			// If the password is empty then set a different error message
		}
	}
	else {
		// Add details to database
	}
}
else
{
	// first time the form has been loaded
	// set all values to blank
}

Open in new window

LB1234

ASKER
Cathal, thanks, I understand that stuff.  I wrote this code.  But I don't fully understand the relationship between if and else statements.  Else statements are "contained" by IF statements, but I need to better understand how nesting works, and how to determine which else statements are contained by a particular if statement.  Why does the last else statement relate itself to first IF statement while the first else statement does not.  I guess I need to understand how nesting really works and why.
LB1234

ASKER
Also, ideally, should the 2nd and 3rd if statements be elseif statements?
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Gary

Else statements are "contained" by IF statements
No - else statements are part of an IF statement - they only fire if the IF condition is not true
To simplify your code - if the form has not been posted (i.e. the submit value is empty) then the ELSE part of the IF statement fires

if(isset($_POST["submit"])) {

}
else
{
      $first_name = "";
      ...
}
SOLUTION
Cornelia Yoder

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
LB1234

ASKER
Yoder, you do realize there are novice coders out there who are doing their best and learning the ropes as they go, correct?  Labeling incorrect approaches as forms of "stupidity" has no place here.  For the benefit of the community stick to addressing the question asked and leave your unhelpful editorializing out of it.
LB1234

ASKER
Gr8, thanks for the explanation.  So if I'm reading you correctly, the second else statement actually applies to the SECOND if statement, even though it works sort of like its an if-else relationship between the first and the last else?  In the example above you indented out the if and the accompanying else statement, so I suppose that leaves the line 13 if to be paired up with line 26 else?


It's one of those situations where the code is technically broken but it still delivers the expected result?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
gr8gonzo

I think yodercrm wasn't calling you stupid, but rather the common practice of putting braces on the same line as the "if" statement.

The spacing is just for readability. I'm not sure I understand what you mean by:
"even though it works sort of like its an if-else relationship between the first and the last else"
SOLUTION
Gary

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
LB1234

ASKER
Ok very sorry yoder!  I misinterpreted what you meant.  OK I finally get it now.  The second if statement has a built in unseen else.  The third if statement has an else right below it, so the else go with that one.  The top if statement pairs up with the remaining else statement at the bottom.  

Got it now!
SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
Cornelia Yoder

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Ray Paseur

+1 for Python which will enforce coding standards!
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes