Solved

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

Posted on 2014-01-06
15
211 Views
Last Modified: 2014-01-07
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

0
Comment
Question by:LB1234
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 3
  • +2
15 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 39759764
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

0
 
LVL 1

Author Comment

by:LB1234
ID: 39759789
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.
0
 
LVL 1

Author Comment

by:LB1234
ID: 39759806
Also, ideally, should the 2nd and 3rd if statements be elseif statements?
0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 58

Expert Comment

by:Gary
ID: 39759819
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 = "";
      ...
}
0
 
LVL 27

Assisted Solution

by:Cornelia Yoder
Cornelia Yoder earned 60 total points
ID: 39759959
If you would use a better indention format, it would be MUCH easier to read.  See attached for example.

      
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


In fact, I have never understood how that incredibly hard to read stupidity of the if formatting you used ever got into coding in the first place.
0
 
LVL 35

Accepted Solution

by:
gr8gonzo earned 250 total points
ID: 39760030
There is ALWAYS a 1-to-1 relationship between an "if" and an "else".

If you had this bit of code:
if($foo == "bar")
{
   echo "Hello world!";
}

Open in new window

You could also think of it as having an invisible "else" that does nothing:
if($foo == "bar")
{
   echo "Hello world!";
}
else
{
}

Open in new window


An "else" never belongs to more than one "if".

So this code:
if($foo == "bar")
{
   if($bar == "foo")
   {
     echo "Hello world!";
   }
}
else
{
}

Open in new window


...can be read as this:
if($foo == "bar")
{
   if($bar == "foo")
   {
     echo "Hello world!";
   }
   else
   {
   }
}
else
{
}

Open in new window


You  just don't always see the empty "else" blocks because the language takes care of that assumption for you.

Also, PHP will let you do "one-line" if/else blocks if you leave out the { and }. So if you see this:
if($foo == "bar")
echo "Hello world";
echo "Blah";

Open in new window

...then it would be the same as this:
if($foo == "bar")
{
  echo "Hello world";
}
else
{
}
echo "Blah";

Open in new window


So the { and } let you specify more than one line of code for if / else blocks. But try not to do that - it's really just bad coding practice and it makes code harder to read, even if it's shorter.
0
 
LVL 1

Author Comment

by:LB1234
ID: 39760143
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.
0
 
LVL 1

Author Comment

by:LB1234
ID: 39760150
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?
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 39760249
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"
0
 
LVL 58

Assisted Solution

by:Gary
Gary earned 20 total points
ID: 39760281
The code is not technically wrong.

The inner IF statements
if ($password !== $password2)
and
if (empty($password))

are separate entities from the outer IF ELSE statement and have no bearing on
if(isset($_POST["submit"])) {

if (empty($password))
is also a separate entity from and has no bearing on
if ($password !== $password2)


Maybe a little read of
http://www.w3schools.com/php/php_if_else.asp
0
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 170 total points
ID: 39760325
@LB1234: The PHP version of this is described in the links.  It's pretty standard in programming languages to have something like this.   What's not pretty standard about PHP is the loose typing of variables and the ways comparison operators may be used to induce type juggling.

Each if() statement contains an expression inside the parentheses.

In addition to if() there is a man page entry for else.  And for elseif.

Expressions in PHP are evaluated into something that is "truthy" or "falsy" depending on the exact nature of the expression.  Falsy values include zero, NULL, the empty string, the empty array and Boolean FALSE (I'm not sure about empty objects).  Everything else will be truthy (I think).  Truthy expressions cause the if() part of the control structure to run.  Falsy expressions cause the else part to run.

Some good learning resources are available in this article.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
0
 
LVL 1

Author Comment

by:LB1234
ID: 39760342
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!
0
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 170 total points
ID: 39760384
YoderCM only calls me stupid, not everyone else. :-)

Here is a hint that will save you a lot of time.  Indent your control structures so that the code lines up in a readable fashion.

This is programmatically correct, but visually incomprehensible.
<?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 {	  	$message = "Please log in";
}

Open in new window

Now that you've seen that, go back to gr8gonzo's example above.  Notice how the curly braces are lined up neatly, starting in the exact same column as the conditional statement that created the control structure?  If you always do that, you will be able to make a quick visual scan of your code to see what might be out of place, and you'll find the answer immediately!
0
 
LVL 27

Assisted Solution

by:Cornelia Yoder
Cornelia Yoder earned 60 total points
ID: 39760386
I'm sorry if you took my comment as criticism of you personally, it was not.

That whole if format structure

if (whatever) {

} else {

}

is commonly taught these days to poor unsuspecting students, who later have the same kind of problem you are having -- difficulty following the code.

The format I showed came from my 30+ years of programming experience, mostly working for IBM, and later in web development, and my PhD studies in computer science, focusing on readability and understandability of code.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39760488
+1 for Python which will enforce coding standards!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses four methods for overlaying images in a container on a web page
This article discusses how to implement server side field validation and display customized error messages to the client.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

710 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question