The road to being a PHP ninja, part 2: Putting PHP to work

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.

The Dalai Lama’s 18 Rules For Living

  1. Take into account that great love and great achievements involve great risk.
  2. When you lose, don’t lose the lesson.
  3. Follow the three Rs:
    • Respect for self
    • Respect for others
    • Responsibility for all your actions.
  4. Remember that not getting what you want is sometimes a wonderful stroke of luck.
  5. Learn the rules so you know how to break them properly.
  6. Don’t let a little dispute injure a great friendship.
  7. When you realize you’ve made a mistake, take immediate steps to correct it.
  8. Spend some time alone every day.
  9. Open your arms to change, but don’t let go of your values.
  10. Remember that silence is sometimes the best answer.
  11. Live a good, honourable life. Then when you get older and think back, you’ll be able to enjoy it a second time.
  12. A loving atmosphere in your home is the foundation for your life.
  13. In disagreements with loved ones, deal only with the current situation. Don’t bring up the past.
  14. Share your knowledge. It’s a way to achieve immortality.
  15. Be gentle with the earth.
  16. Once a year, go someplace you’ve never been before.
  17. Remember that the best relationship is one in which your love for each other exceeds your need for each other.
  18. Judge your success by what you had to give up in order to get it.

The road to being a PHP ninja, part 1: Introduction to PHP

So, what is PHP?

PHP

I’m sure you’ve heard of it (and that’s why you’re here), but you probably don’t know how useful and nifty PHP actually is. PHP is seen in pretty much every asset of the Internet, from Facebook to this blog, it’s everywhere. But why?

PHP is (to say the least) an amazing language for beginners and professionals alike. It’s a very dynamic and powerful, but simple. It’s also free and who doesn’t like free?

I love PHP, so my goal with these tutorials is to help anyone I can learn and write it. By the time you finish these sets of tutorials you’ll be a skilled PHP ninja and maybe even teaching it to someone else.

A place to settle down

Before we begin, we should find a place to actually write your code. PHP is often installed on servers with Apache or Lighttpd. For the sake of this tutorial, you can probably google “Free PHP host” and just test your code in there or use XAMPP (windows) or MAMP (OS X) to develop on your computer. I won’t guide you through this process, but it’s mostly step-by-step.

This series will be based on PHP 5.3 running on Apache in OS X.

Let’s dive on in

One of the things that makes PHP such an easy language for new comers is that you can (but that doesn’t mean you should) mix HTML and PHP. Since you’re a beginner, we’ll let you grasp that before plunging into higher concepts.

To define PHP code in a document, you simply begin with:

[php]
<?php
//Your PHP Code
?>
[/php]

Simple enough? Two things to note, however.

First, notice the two slashes on line 2, those are for commenting in PHP without the interpreter rendering them. It helps you keep track of your code as it grows.

Second, on line 1 we started with a < ?php. However, < ? is also an acceptable opener, but keep in mind this may be disabled on some servers so using the first method makes your coding much more portable.

Let’s see some PHP in action now:

[php]
<html>
<head>
<title>Oh yeah</title>
</head>
<body>
<em>You didn’t think it was gonna be that easy, did you?</em>
<br /><br />
<?php echo "You know, for a second there, yeah, I kinda did."; ?>
</body>
</html>
[/php]

Above is how you integrate PHP into an HTML document. Line 7 is the only new thing (assuming you know HTML, I hope) and we’ll talk about it below. First, let’s see what the HTML output will be:

[php]
<html>
<head>
<title>Oh yeah</title>
</head>
<body>
<em>You didn’t think it was gonna be that easy, did you?</em>
<br /><br />
You know, for a second there, yeah, I kinda did.
</body>
</html>
[/php]

So, what’s happening? You see the familiar < ?php followed by the word echo. echo() is a special function as it does not require parentheses for it’s options. However, the same line can be written a few different ways:

[php]
<?php echo("You know, for a second there, yeah, I kinda did."); ?>
<?php print("You know, for a second there, yeah, I kinda did."); ?>
[/php]

print() has the same function as echo, but requires parentheses.

Also worth noting is that the semi-colon at the end. A common mistake is to forget to include it which will cause PHP to throw an error. However, it’s worth noting that you do not need the semi-colon at the end of your PHP script. The example below is perfectly acceptable:

[php]
<?php echo "Revenge is a dish best served cold" ?>
[/php]

The Variable

Variables are not unique to PHP and even if you haven’t had any experience with them, they’re quick to catch on. Wikipedia describes a variable as:

In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents. A variable name in computer source code is usually associated with a data storage location and thus also its contents, and these may change during the course of program execution.

In a shorter, more readable definition: a variable stores information that can be used later. Used for what? They can be used to store data that can be rendered to HTML or used for comparisons. Variables are the core to the flexibility of PHP.

Variables can be various things, including strings (text), integers (full numbers), point numbers, and arrays (a collection of data) but unlike other languages, PHP is smart with it’s variable type assigning; PHP can use it’s superpowers to determine what kind of variable you want without having to manually specify it.

A variable is just a name behind a dollar ($) sign. There are not many requirements for variable names other than they are case-sensitive and must start with a letter or underscore (meaning not a number), after that they can contain numbers, letters, and underscores. Examples are $world, $_framework, and $profile1. Variable like $42 or $53variable won’t work and will throw an error.

Let’s see an example that incorporates variables:

[php]
<html>
<head>
<title></title>
</head>
<body>
<?php
//Here we are defining variables

$bills_speech = "No Kiddo, at this moment, this is me at my most… masochistic.";
$kiddos_speech = "Bill… it’s your baby.";

echo "<strong>Bill:</strong> ".$bills_speech." <br /><br /><strong>Nameless:</strong> ".$kiddos_speech;
?>
</body>
</html>
[/php]

In this example we set up the variables by defining their name (e.g., $bills_speech) and their strings, separated by a equals (=). You can see them integrated into the echo() function by “.. The equals ends and starts the string while the period connects the variable. This is how you integrate strings with your variables, which can be very useful.

Defining variables of other types are just as easy:

[php]

// A string, which we saw before. A string can be defined with double
// or single quotes and strings. Use a backslash to allow quotes inside
// of another quote.

$string = "The Bride: "Wiggle your big toe."";

//Integers are full numbers defined without quotes:
$integer = 42;

//Floating points are the same, with a decimal:
$float = 3.14;

//And defining boolean values can be done by putting true or false:
$boolean = true;
[/php]

Working with strings

Working with strings is a very common thing to do. Strings are dynamic and contain a lot of information. Remember how you used the period (“.“) above to stick a variable to an existing string? Well, to combine variables you can use the exact same thing.

[php]
<?php
$tagline = "Gotta catch em all! <br />";
$endline = "POKEMON!";

$tagline = $tagline.$endline; //Echoed: "Gotta catch em all <br />POKEMON!"

//You can condense this even further. Below represents the exact same thing:
$tagline .= $endline;
?>
[/php]

Wrapping it all up

This is it for this tutorial. Hopefully after working with this tutorial you have a grasp on some of the contexts of PHP. In the next we will be looking at applying these concepts to really see how amazing PHP is and what you can do with it.