Basic Conditionals
In the simplest sense, all decisions are made based on a condition: something that may or may not be true.
To see this, look at a few of the decisions you might make from day to day:
If it’s trash day, take the trash to the curb.
If the car is low on gas, stop and fill it up.
If it’s raining, take an umbrella.
Notice that all of these statements follow a certain pattern: A condition is given, and then an action is given that should be performed if and only if the condition is true.
Thus, if it’s trash day and you consider the first example, the condition (whether it’s trash day) will be true. So, you take the trash to the curb (or tell somebody else to do it).
The if statement specifies a command (or multiple commands) that should be executed if a given condition is true. An if statement evaluates its condition as a Boolean expression; if a condition doesn’t result in a Boolean value, it is typecast to a Boolean.
NOTE
You may wish to review Chapter 2, “Variables and Constants,” for information about Booleans and the rules followed by PHP in typecasting other types to Booleans.
The if statement follows this syntax:
if (condition)
{
statements
}
[ else
{
statements
} ]
NOTE
The lines enclosed in braces are collectively called a block.
Condition is any statement or expression that evaluates to true or false. Statements may be one or more statements formatted just as any other PHP statements would be formatted, except indented one level deeper (usually four spaces or one tab) for good style. The optional else keyword and block allow you to execute a different set of statements when the condition is false. else will be discussed later in this chapter, in “Using elseif and else Statements.”
The following example helps demonstrate the syntax to use with if statements:
<?php
/* ch06ex01.php – demonstrates simple use of if statement */
// Condition 1
if (true)
{
echo "Condition 1 outputs this.";
}
// Condition 2
if (false)
{
echo "Condition 2 outputs this.";
}
?>
When you run this program, only the following text appears:
Condition 1 outputs this.
The first if statement finds that the condition specified in parentheses is true, so it executes the command given after it in curly braces. (If you want the condition to execute multiple commands, you can place the additional commands inside the curly braces.)
The second if statement doesn’t allow the code below it to execute, though, because the condition it’s given is explicitly given as false.
NOTE
The previous example always prints the result as shown.
Code such as this, however, has no practical use; if you’re just going to specify true or false as the condition, you might as well leave the if statement out altogether. Instead, if statements are more appropriately used with variables and constants.
The following program shifts from using explicit true/false values, which aren’t very useful in a practical program, to using variables that will evaluate to a true or false value (all variables evaluate to one or the other, depending on their value):
<?php
/* ch06ex01.php - demonstrates simple use of if statement */
$condition1 = 1; // Evaluates to true
$condition2 = 0; // Evaluates to false
// Test condition 1
if ($condition1)
{
echo "Condition 1 is true.";
}
else
{
echo "Condition 1 is false.
\n";
}
// Test condition 2
if ($condition2)
{
echo "Condition 2 is true.
";
}
else
{
echo "Condition 2 is false.
";
}
?>
The output from this program is
Condition 1 is false.
Condition 2 is true.
Almost all statements, namely function calls, have a value associated with them. For example, preg_match evaluates to 1 if a match is found; otherwise, it returns 0.
NOTE
When functions, such as preg_match, evaluate to a value, it’s commonly said in the programming vernacular that the function “returns” the value. When a value is said to be returned, it is the same as if the function evaluated directly to that value.
To learn more about return values, see “Returning a Value,”.
The following example demonstrates the use of a function’s return value:
<?php
/* ch06ex02.php – demonstrates function's return value */
$intFirstResult = preg_match('/abc/', 'abcdef'); // match found, evaluates to 1
$intSecondResult = preg_match('/abc/', 'defghi'); // match not found, evaluates to 0
echo "\$intFirstResult = $intFirstResult
";
echo "\$intSecondResult = $intSecondResult
";
?>
This program yields the following output:
$intFirstResult = 1
$intSecondResult = 0
Thus, you can see that the first call to preg_match returns true, and the second call returns false (both represented here numerically).
Such a return value is often evaluated within an if statement. For example, to see if “abc” is found in “abcdef”, an if statement such as the following could be constructed:
<?php
/* ch06ex03.php – tests whether string is found */
// initialize variables
$strContainer = 'abcdef';
$strFirstTest = 'abc';
$strSecondTest = 'ghi';
// See if $strFirstTest is in $strContainer
if (preg_match("/$strFirstTest/", $strContainer))
// notice the double closing parenthesis; one for
{
// preg_match and one for the if statement
echo "'$strFirstTest' was found in '$strContainer'";
}
// Separate first result from second result with an HTML line break
echo "
";
// See if $strSecondTest is in $strContainer
if (preg_match("/$strSecondTest/", $strContainer))
{
echo "'$strSecondTest' was found in '$strContainer'.";
}
?>
Since only $strFirstTest is found in $strContainer, the output is
‘abc’ was found in ‘abcdef’.
Try this program with other values, if you wish. Add the contents of $strSecondTest to $strContainer, for example, to see how the second if statement reacts when a match is found.
Using elseif and else Statements
Many times, you don’t want to do something only if a condition is true, but also do something if it isn’t true. For example, using preg_match as shown previously, you might wish to tell a visitor whether a match was found or not. Therefore, you must output something depending on if the call to preg_match succeeds or fails, but the program must never output both statements.
This is accomplished using an else statement, which follows this syntax:
if (condition)
{
statements
} else {
other-statements
}
NOTE
When if and else statements are combined, they can be referred to collectively as an if-else clause.
So, to tell a visitor whether a match was found, you could use
<?php
/* ch06ex04.php – tells visitor whether match was found or not */
// initialize variables
$strContainer = 'abcdef';
$strFirstTest = 'abc';
$strSecondTest = 'ghi';
// See if $strFirstTest is in $strContainer
if (preg_match("/$strFirstTest/", $strContainer))
// notice the double closing parenthesis; one for
{
// preg_match and one for the if statement
echo "'$strFirstTest' was found in '$strContainer'";
} else {
echo "'$strFirstTest' was not found in '$strContainer'";
}
// Separate first result from second result with an HTML line break
echo "
";
// See if $strSecondTest is in $strContainer
if (preg_match("/$strSecondTest/", $strContainer))
{
echo "'$strSecondTest' was found in '$strContainer'";
} else {
echo "'$strSecondTest' was not found in '$strContainer'";
}
?>
Running this program produces the following output:
‘abc’ was found in ‘abcdef’
‘ghi’ was not found in ‘abcdef’
As you can see, the program now has a reaction for both conditions: If the match is found, it says one thing, but if a match isn’t found, it says another.
You may also have a certain series of conditions, for each of which you wish to perform a certain task. In English, this would equate to: “If condition A is true, do this; or if condition B is true, do this; otherwise, do this.” There could be more conditions checked, as well; they would be phrased like condition B.
For example, let’s assume you want to place someone into a four-category age-grouping system. The age groups are divided as follows:
Group A—Ages 20 and younger
Group B—Ages 21 to 40
Group C—Ages 41 to 60
Group D—Ages 61 and older
This involves using a combination of if, elseif, and else to find which age group is appropriate and assign the corresponding letter to a variable.
TIP
The less than operator (<) is used in this example; it is introduced in more depth a bit later in this chapter.
Basically, an expression using the less than sign evaluates to true if the left operand is less than the right operand.
Here's the program:
<?php
/* ch06ex05.php – assigns an age group for the specified age */
// Grab $intAge from POST array
$intAge = $HTTP_POST_VARS['age'];
// If the form has been submitted
if ($intAge) // will be true if it's been submitted (can't be 0)
{
// Assign age group letter to $chrAgeGroup
if ($intAge < 21) // Ages 20 and younger
{
$chrAgeGroup = 'A';
} elseif ($intAge < 41) { // Ages 21 – 40
$chrAgeGroup = 'B';
} elseif ($intAge < 61) { // Ages 41 – 60
$chrAgeGroup = 'C';
} else { // Ages 61 and older
$chrAgeGroup = 'D';
}
// Show age group chosen
echo "Age $intAge fits into age group $chrAgeGroup";
}
?>
<!-- Here's the HTML form we get input from -->
<form action="ch06ex05.php" method="POST">
Age: <input type="text" name="age"><input type="submit">
</form>
Here are some samples of the program’s output:
Age 14 fits into age group A
Age 37 fits into age group B
Age 99 fits into age group D
NOTE
Notice the difference here between an if-else clause and multiple if statements. If multiple if statements were used and the age were, say, 20, not only would that condition be true (assigning ‘A’ to $chrAgeGroup), but the two conditions following it would be true also because 20 is less than 41 and 20 is less than 61. Thus, only the last value, ‘C’, would be assigned to $chrAgeGroup, and the age group assigned would be incorrect.
You can also nest if statements; that is, you can include one or more if statements within the statements surrounded by another if statement. Thus, you can check one condition, and if it is true, you can check another condition and perform different actions depending on the inner condition. (The inner if statement, in effect, is evaluated only if the outer one is true.)
Nested if statements can be nested to any number of levels, as shown here:
if (condition)
{
if (condition)
{
if (condition)
{
if (condition)
{
// etc.
}
}
}
}
Each condition represents a condition you want to test. Each of these if statements may also have accompanying elseif and else statements, as necessary.
For example, the following program improves Example 5 to determine whether the input submitted is numeric before it tries to determine the number’s category; if for some reason something other than a number is submitted, an error message is displayed.
<?php
/* ch05ex06.php – demonstrates nested if statements */
// Grab $intAge from POST array
$intAge = $HTTP_POST_VARS['age'];
// If the form has been submitted
if ($intAge) // will be true if it's been submitted (can't be 0)
{
if ( is_numeric($intAge) ) // A number was given
{
// Assign age group letter to $chrAgeGroup
if ($intAge < 21) // Ages 20 and younger
{
$chrAgeGroup = 'A';
} elseif ($intAge < 41) { // Ages 21 – 40
$chrAgeGroup = 'B';
} elseif ($intAge < 61) { // Ages 41 – 60
$chrAgeGroup = 'C';
} else { // Ages 61 and older
$chrAgeGroup = 'D';
}
// Show age group chosen
echo "Age $intAge fits into age group $chrAgeGroup";
}
else // It wasn't a number; print an error message
{
echo "You must enter a number!
";
}
}
?>
<!-- Here's the HTML form we get input from -->
<form action="ch06ex06.php" method="POST">
Age: <input type="text" name="age"><input type="submit">
</form>
NOTE
The is_numeric function is very straightforward: It takes one argument and returns true if the argument is a number; otherwise, it returns false.
The if statements here are nested—there’s one that has most of the rest of the program in its code block. Then, the second if has yet another if within its code block. This way, your program can perform different tasks based on the conditions.
NOTE
The indentation shown here is an important attribute of programming style.
As mentioned in Chapter 1, “Welcome to PHP,” the indentation brings much clarity to the organization of your program. The if statements above would surely be harder to evaluate if they were all aligned even with the left edge. By indenting each if block to a new level, you demonstrate visually that program execution will never make it to the inner (indented) levels without first passing through the conditions given by the outer levels (to the left of the current level).
So, for program execution to reach the innermost level of three levels, all three conditions must be met. Indenting each block of code makes this relationship obvious on first sight—instead of forcing someone reading your code to match curly braces to find where blocks begin and end.
The if statements you’ve explored so far evaluate only a single value that is either true of false; many times, though, you’re not at all interested in whether a value is simply true or false. Rather, you’re interested in how one value compares to another.
Here are a few examples:
Is $intA less than $intB?
Does $strA have the same value as $strB?
Is $form[’emailAddress’] empty, or does it contain something?
These comparisons can all be made using conditional operators, which are operators that compare two values and return a Boolean value.
NOTE
Because of their purpose, conditional operators are sometimes referred to as comparison operators.
The syntax for conditional operators is the same as other binary operators; that is, one value should be placed on each side of the operator, as shown here:
value operator value
Table 6.1. The Comparison Operators Operator Name Example
== Equal $var1 == $var2
=== Identical $var1 === $var2
!= Not equal $var1 != $var2
!== Not identical $var1 !== $var2
> Greater than $var1 > $var2
>= Greater than or equal to $var1 >= $var2
< Less than $var1 < $var2
<= Less than or equal to $var1 <= $var2
NOTE
The == and === operators (and their != and !== relatives) aren't the same. The first, which checks two values for equality, compares two values of the same data type. If they aren't the same type, == typecasts them before they are compared. Therefore, the string "1" and the integer 1 are the same.
On the other hand, === checks each value's type before comparing the actual value. If the types don't match, the variables aren't considered the same, and false is returned. Only if two variables are identical (that is, their type and value both match) will this operator return true.
To use an if statement to see whether a form field was filled out, you could use
if ($form['username'] == '')
{
echo 'You must enter a username.';
}
As you can see, this tests to see if $form[’username’] is an empty string or not.
NOTE
This example assumes that a reference called $form has been made from $HTTP_POST_VARS or $HTTP_GET_VARS, whichever is appropriate.
TIP
The isset() and empty() functions are also sometimes used for this purpose. However, isset() tests only whether a variable has been declared (thus it could be empty). The empty() function considers “0″ and “” to both be the same, so even if “0″ is a legitimate choice, it will be rejected because it is considered by empty to be the same as “”.
Therefore, the best way to test if a form field was filled or not is to test to see if it is equal or not equal to an empty string.
Let’s try using this technique to create a single-page login form. (This will later be expanded into a file that can ensure a user is logged in for any number of pages.)
The file should react depending on the data passed to it. For starters, if a username and password aren’t supplied, a login form should be shown requesting this information. This is what happens the first time that a user goes to the page.
Once a username and password are supplied, they should be verified for correctness. If they’re not correct, the login form should be returned with an error message stating that the username and password weren’t accepted. If they are correct, the user should be shown whatever is being protected on the page.
Since this program performs several different tasks, let’s divide them up so you can see how the tasks relate to each other. Here’s a flow chart showing the different tasks the program will perform:
Figure 6.1. This flow chart illustrates the path Example 6’s logic will follow.
From this, you know that the program must make two decisions: whether data has been posted, and, if so, whether the data is the correct username and password. Also, since you’re passing username and password information, you’ll be using the post method; thus, you’ll create a reference called $form to $HTTP_POST_DATA. Here’s a program skeleton with the code for these first two requirements:
<?php
/* ch06ex06a – login form program skeleton showing structure of if statements */
// define allowed username/password pair
define('ALLOWED_USER', 'administrator');
define('ALLOWED_PASS', 'abc123');
// create reference to form based on the form method used
$form =& $HTTP_POST_VARS;
if ( ($form['username'] == '') || ($form['password'] == '') )
{
// Show a login form
} else {
if ( ($form['username'] == ALLOWED_USER) && ($form['password'] == ALLOWED_PASS) )
{
// User verified OK; return protected page
} else {
// User provided bad login info; return login form with error message
} // end if
} // end if
?>
NOTE
The && operator means “and”; it’s a logical operator that we haven’t discussed yet, but its purpose here should be clear. Only if both conditions are true will the whole condition evaluate to true.
The || operator evaluates to true if either condition is true.
These and the other logical operators are discussed later in this chapter.
Notice that the first if statement only checks to see if a username and password were submitted. Whether the password is actually correct or not is determined by a nested if statement after the program has determined that there is a username and password pair to test in the first place.
The benefit of the nested if statements is that different pages can be shown depending on the conditions. If the username and password simply aren’t given, a basic login form can be displayed to request the missing data. On the other hand, if the username and password were given but are incorrect, a different page can be shown stating that the data provided was not accepted and a form can be provided to allow the user to try again.
Here’s how you would complete this program:
<?php
/* ch06ex06b – login form program */
// define allowed username/password pair
define('ALLOWED_USER', 'administrator');
define('ALLOWED_PASS', 'abc123');
// create reference to form based on the form method used
$form =& $HTTP_POST_VARS;
if ( ($form['username'] == '') || ($form['password'] == '') )
{
// Show a login form
?>
<html>
<head><title>Chapter 6 :: Example 6 :: Login Form</title></head>
<body>
<h2>Login</h2>
<form action="<?= $PHP_SELF ?>" method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit" value="Login">
</form>
</body>
</html>
<?php
// End of login form
} else {
if ( ($form['username'] == ALLOWED_USER) && ($form['password'] == ALLOWED_PASS) )
{
// User verified OK; return protected page
?>
<html>
<head><title>Chapter 6 :: Example 6 :: Protected Page</title></head>
<body>
<h2>Login Successful</h2>
This page would contain the protected information, such as management
facilities for the site, information intended for only a certain person
or group of people, etc.
</body>
</html>
<?php
// End of protected page
} else {
// User provided bad login info; return login form with error message
?>
<html>
<head><title>Chapter 6 :: Example 6 :: Login Form – Error</title></head>
<body>
<h2>Login</h2>
<h4>The username and password you entered were not valid.</h4>
<form action="<?= $PHP_SELF ?>" method="post">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit" value="Login">
</form>
</body>
</html>
<?php
// End of login form with error message
} // end if
} // end if
?>
TIP
The $PHP_SELF variable is defined by PHP to be a valid URL for the script being accessed. Thus, having a form post to $PHP_SELF ensures that no matter what the file is named or where it is, it will always submit to its own address.