The if
statement is one that is central to all scripting languages. In PHP, the basic syntax is:
if (condition) { result; }
Our condition goes within parentheses, while the result – what we want to have happen if the condition is met – goes within curly braces. Our result could be many lines long; and, as we’ll see shortly, it need not be PHP.
The simplest statement one could make would be something like the following:
<?php if ($_POST['userName'] == "Nom") {
echo "<p>Welcome, mighty SuperUser!</p>";
} ?>
It’s very important to note the double equal sign (==
), known as the comparison operator. A single equals sign sets a variable to a particular value; a double equals sign compares a variable to a value.
While that example works, it’s rare that you would be testing against a single, known value. It’s more likely that you simply want to know if the username
field had been filled out with anything at all:
<?php if ($_POST['userName'] != "") {
echo "<p>You’ve filled the field</p>”;
} ?>
We’ve used the not equal to (!=
) operator to compare what has been entered into the field to blank (two quote marks right next to each other). If that is the case, we echo
out a paragraph.
The logic could be reversed to make the opposite statement:
<?php if ($_POST['userName'] == """) {
echo "<p>You have <em>not</em> filled the field</p>";
} ?>
This statement could also be written as:
<?php if (!$_POST['userName']) {
echo "<p>You have <em>not</em> filled the field</p>";
} ?>
One other alternative:
<?php if (!isset($_POST['userName'])) {
echo "<p>You have <em>not</em> filled the field</p>";
} ?>
In this case, the not operator is moved before the variable. Essentially we are saying “if not variable” i.e. if the variable does not exist, do what follows as the action.
If there are multiple variables to compare, we can use the and or or comparison operators:
<?php if (!$_POST['userName'] && !$_POST['password'] ) {
echo "<p>You have left both fields empty.</p>";
} ?>
<?php if (!$_POST['userName'] || !$_POST['password'] ){
echo "<p>You have left <em>one</em> of these fields empty.</p>";
} ?>
The single best feature of PHP conditions is the fact that our result may be phrased as any kind of code or content. In our examples, we have been using echo
to print our responses to the page. However, there is nothing dynamic about our responses, nor are we saying anything that couldn’t be stated in HTML. Returning to our first example, then, we could close the PHP early, and do the response in HTML:
<?php if ($_POST['userName'] == "Dudley") { ?>
<p>Welcome, mighty SuperUser!</p>
<?php } ?>
This gives us the exact same results, but uses far less code. The only requirement is that we close the PHP after the opening brace, and reopen it to capture the closing brace. Between the two we could place anything: HTML, CSS, JavaScript, even more PHP.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.