In the first part of this series, we learned how exactly PHP works and functions. We learned how to call PHP within a file, the basic functions echo() and print(), and how to work with variables. It didn’t seem that hard, now did it?
One of the most common things PHP is used for is capturing data from a user and then doing something with it, such as storing it in a database or displaying back. Today we are going to step you into that process to show how simple it can be.
Setting up the form
Forms are everywhere on the net and the primary way that users input information into websites. Let’s start with something simple:
[php]
//index.php
<html>
<head>
<title></title>
</head>
<body>
<form action="name.php" method="post">
<input type="text" name="name" value="Your name" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
[/php]
Above is a simple HTML skeleton with a form tag and a couple of input tags nested inside. The beef of this is the form which will capture the data entered into your inputs and send them to “name.php” which is shown by the attribute action=”name.php”.
The method=”post” attribute describes that we will be sending the request with a POST header.
Adding function to your form with PHP
Before you submitted the information from your form to “name.php” so we should create that file next.
[php]
//name.php
<html>
<head>
<title></title>
</head>
<body>
<?php
//Get the name from $_POST
$name = $_POST[‘name’];
echo "<h2>Hello ".$name."</h2>";
?>
</body>
</html>
[/php]
See what we did there? If not, let me break it down for you:
$_POST is a special PHP variable that gets the POST parameters of a form. Basically, when you create a form with action=”post”, the inputs are assigned to the $_POST array (but what’s an array? We’ll get back to that in a little). You can then get the value of the input by using the input’s “name”.
PHP also supports the GET method as well. Represented by a $_GET array, the GET parameter can be instead used on your form with method=”get”.
Making decisions
One of the core functions of PHP is to make decisions based on a conditional statement and act on that decision. This makes your scripts smarter skynet* and able to do various actions based on the result from this statement.
To help determine the result of a conditional statement, you will most commonly use the <, >, =, and ! operators. Let’s see how to set these up in PHP:
[php]
<?php
// We need to define some variables:
$one = 1;
$three = 3;
$s_one = "1";
$boat = "boat";
$test1 = ($three > $one); // $test1 will equal true.
$test2 = ($three < $one); // $text2 will equal false.
?>
[/php]
Let’s start with this. $test1 is the test of 3 being greater than (>) 1. Since this is true, the condition returns true. $test2 is the exact same conditional statement except that we switch the greater than (>) to a less than (<). Because 3 is not less than 1, the statement returns false.
[php]
<?php
// Keep the variables the same
$one = 1;
$three = 3;
$s_one = "1";
$boat = "boat";
// This time we add a "=" after the ">" to make it "greater than or equal to"
// "3 is greater than or equal to 3"
// $test3 will equal true
$test3 = ($three >= $three);
// We do the same as we did above…
// "3 is less than or equal to 1"
// $test4 will equal false
$test4 = ($three <= $one);
// We can also see if variables equal each other
// $test5 will equal true.
$test5 = ($one == $s_one);
// PHP also includes a way to check a variable’s value AND type
// The below will return false because $one is a integer and
// $s_one is a string.
$test6 = ($one === $s_one);
// To see if things do not equal each other, we use the "!"
// $test6 will equal true.
$test7 = ($boat != $s_one);
//In $test7, we can also use "<>" in place of "!="
?>
[/php]
Compounding smarts
The comparison operators are also complimented by a set of four logical operators. The purpose of these logical operators are to group your conditional statements together to create a larger and more dynamic statement. These operators are AND, OR, NOT, XOR.
Let’s see them in action:
[php]
<?php
// Create some variables:
$one = 1;
$two = 2;
$three = 3;
$one2 = 1;
// The logical AND (represented by "&&") returns true if all conditional statements are true
// The below returns false.
$test8 = (($one == $one2) && ($one == $two));
// The logical OR (represented by "||") return true if one or more conditional statements are true.
// $test9 returns true.
$test9 = (($one == $one2) || ($one == $two));
// The logical NOT (represented by a "!") returns false if the conditional statement is true and vice-versa.
// $test10 returns false.
$test10 = !($one == $one2);
// And last (but not least!), the logical XOR (represented by "XOR") returns true if one conditional statement is true
// and false if they both are true.
// The below will return false.
$test11 = (($one == $one2) XOR ($one == 1));
?>
[/php]
Logical operates are just as simple as operators used in conditional statements. They are important because they allow you to group your conditional statements logically and without mucking up your PHP.
A function for everyone
Now that you understand conditional and logical operators, you can make your scripts act on the decisions made by your conditional statements. To do this, you need to take advantage of the if() function:
[php]
if(condition)
{
//This happens
}
[/php]
if() accepts an argument that can be a conditional statement which is evaluated to a true or false. If the conditional statement is true, then if() executes the code inside of your curly brackets. If not, the code in your brackets is skipped.
Let me extend my name script above to show another example with if():
[php]
//name.php
<html>
<head>
<title></title>
</head>
<body>
<h2>
Hello
<?php
//Get the name from $_POST
$name = $_POST[‘name’];
if($name == "Beatrix Kiddo") {
echo "****";
} else {
echo $name;
}
?>
</h2>
</body>
</html>
[/php]
Along with showing a live example of if(), we also created an if-else construct. This is the else after the if()‘s brackets, and contains its own set of brackets. This second set of brackets is executed if your conditional statement returns false. Don’t get it in your head that else is required; omitting else will just cause nothing to happen in the case of your conditional statement returning false.
Compressing your statements
PHP includes a few tricks to shrink your statements.
The ternary operator, which is represented by a question mark (?), allows you create single statement if-else blocks. For example, the code on lines 14 through 18 in the example above can be written as:
[php]
<?php echo ($name == "Beatrix Kiddo" ? "****" : $name); ?>
[/php]
The drawback of using the ternary operator is that you lose the logical flow of PHP, which makes it harder for people to read. The ternary operator is best used in templates (using templates to separate your PHP and HTML is a more advanced topic for one rainy day later).
Another method to compress your statements is something you already know: logical operators. Using logical operators allows you to compress nested if() functions:
[php]
<?php
//Nested if() functions…
if($name != null) {
if($name != "Beatrix Kiddo")
{
echo $name;
}
}
//Can be combined using the logical operators.
if($name != null && $name != "Beatrix Kiddo")
{
echo $name;
}
?>
[/php]
This allows you code to be a lot more readable and prevents you from using extra of lines. Overall, the latter method should be used as much as possible.
Wrapping it all up
That’s about it for this tutorial. Hopefully by the end of it, you understand conditional and logical operators and have a grasp on one of the most important PHP functions, if(). Reading over this tutorial a few times is something you should do; by memorizing the conditional and logical operators, you’ll be able to write PHP faster than having to constantly looking them up.
In our next tutorial we will be stepping you into more advanced structures, variables types, and a few smarter scripts.