Jump to content

if and elseif


ngreenwood6

Recommended Posts

I have the following code:

 


//Make the error variable
$error = "";

if(!$username)
{
$error .= "Please enter a username!";
}
elseif(!$password)
{
$error .= "Please enter a password!";
}
elseif($username != $row['username'])
{
$error .= "Please enter a valid username!";
}
elseif($encrypted_password != $row['password'])
{
$error .= "That password is incorrect!";
}
elseif($error != "")
{
echo $error;
}

 

The problem is that if there is an error it doesn't display anything. When I try to display the error it just shows a blank page. Can someone help?

Link to comment
https://forums.phpfreaks.com/topic/135861-if-and-elseif/
Share on other sites

According to what you wrote, $error == "" is true unless there is at least one error, whichever the first error that is triggered will set $error to something not "". By testing if( $error != "" ) at the end will only be true if at least one error is found.

 

I can at least tell you the elseif( $error != "") will not run after an error has been triggered in your elseif sequence and, from just that snippet of code, it will not run if an error isn't triggered.

 

Elseif will leave a line of elseif conditions once ONE of them has been triggered. If you had a sequence of 10 elseifs and the last 5 were true, only the 5th would've execute code and the rest would have not been touched.

Link to comment
https://forums.phpfreaks.com/topic/135861-if-and-elseif/#findComment-708235
Share on other sites

moejoe22 hit the nail on the head. Get rid of your last elseif, and test if $error contains anything separately:

 

Indenting statements inside blocks helps improve readability...

<?php

$error = '';

if(!$username)
{
  $error = "Please enter a username!";
}
elseif(!$password)
{
  $error = "Please enter a password!";
}
elseif($username != $row['username'])
{
  $error = "Please enter a valid username!";
}
elseif($encrypted_password != $row['password'])
{
  $error = "That password is incorrect!";
}

// now check for errors
if (!empty($error))
  echo $error;

?>

 

Like mojoe22 said, only one branch will execute, this is not a switch statement (without a break). Therefore, there is no reason to concatenate. The first branch found to be true will be executed, and then execution moves past the rest of the branches.

 

An alternative approach would be setting up some error flags that hold bit masks, which would be a pretty easy way to test for multiple errors.

Link to comment
https://forums.phpfreaks.com/topic/135861-if-and-elseif/#findComment-708245
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.