Author

TheDesignJunkie.com is the blog of Cole Hicks. Cole is a web designer, consultant, and computer book author covering topics related to graphic design, the web, and web 2.0 technology.

Newsletter

    Weekly newsletter packed full of the latest web design tips, tutorials. It's free to subscribe and you can opt-out at any time.

PHP Tutorial 12 | Working with Forms, $_POST, $_GET, and $_REQUEST Variables

18 November 2007 - 1:36

In PHP Tutorial 11 we covered the basics of working with forms in PHP. In that tutorial we created a simple “contact us” form. We used the POST method in our HTML. In this section we are going to discuss the variables that relate to both the POST and GET methods. Those are $_POST, $_GET, and $_REQUEST variables. By the time you are finished with this tutorial you’ll have a solid understanding of how and when to use each.

$_POST and $_GET

You may already have an idea about how these two variables work from your experience with HTML. The fundamental difference between GET and POST is that GET can be encoded into a URL while POST is invisible. The variables $_POST and $_GET relate to the specific methods. If you use the POST method in your form then you would use the $_POST variable to retrieve and array of each of the different values sent in the form. If you used the GET method you would use the $_GET variable to retrieve the array of values.

When to Use POST and When to Use GET

In it’s simplest form people use GET for retrieving data, and they use POST for sending data. For example GET is common in search forms. With get you can store the request in a URL string. This means that it can be bookmarked. So if you created a search and wanted to bookmark it so you could always get to the results page you could. One other point to note is that the GET URL string can only contain 100 characters. POST on the other hand can contain an unlimited number of characters and since it is not something that you see in a URL string, it is often used for sending things like passwords, emails, or communications that you don’t want to show up in a URL string.

Here is an example:


<form action="usr_details.php" method="post">
First Name: <input type="text" name="first_name">
Last Name: <input type="text" name="last_name">
Email Address: <input type="text" name="email">
<input type="submit">
</form>

Saving this form and opening it up in a browser you’ll notice that when you click on submit you see only:

http://www.YOUR_URL.com/usr_details.php

None of the information submitted in the form shows up in the URL. If you had used the GET method you would see something like this instead:

http://www.YOUR_URL.com/usr_details.php?first_name=Bob&last_name=Smith&email=bsmith%40test.com

In the PHP script that we use to process the form data (usr_details.php) we simply use the $_GET and $_POST variables where appropriate depending on which method you used (POST or GET). If we were using POST and wanted to print the data that was sumbited on screen we would code something like this:

<?php
echo "<p>".$_POST["first_name"]."<br />";
echo $_POST['last_name']."<br />";
echo $_POST['email']."</p>";
?>

If we were using GET and wanted to print the data that was sumbited on screen we would code something like this:

<?php
echo "<p>".$_GET["first_name"]."<br />";
echo $_GET['last_name']."<br />";
echo $_GET['email']."</p>";
?>

Again, the big difference is that when the form is submitted and processed the URL string that shows is either something like:

http://SOME_URL.com/usr_details.php?first_name=Bob&last_name=Smith&email=bsmith%40test.com

Or if you used post it would look something like:

http://SOME_URL.com/usr_details.php

The $_REQUEST Variable
The last variable that you can use is the $_REQUEST variable. This variable is very useful because it contains information related to both POST and GET along with any cookies that have been set. We’ll discuss cookies in more detail in later tutorials. For now just know that you can use the $_REQUEST variable to retrieve information on both GET and POST along with cookies. Similar to $_GET and $_POST the code looks like this:

<?php
echo "<p>".$_REQUEST["first_name"]."<br />";
echo $_REQUEST['last_name']."<br />";
echo $_REQUEST['email']."</p>";
?>

[ Go back to PHP Tutorial 10 | Using External File Includes in PHP ]

2 Comments | Tags: PHP

PHP Tutorial 11 | Working with Forms in PHP

6 November 2007 - 4:57

There are a couple ways to create forms in PHP. You can create a form in HTML that executes a PHP script in a separate file, or you can include both the form and the script in the same page. For our purposes we’ll include them both in the same page. This is how I like to develop most PHP forms and it saves a bit of time when calling the page up in a web browser.

In this example we’ll create a simple Contact Us form and use PHP to send a message to an email address that we specify.

Step One, Display or Not

The first bit of code we are going to write will tell us whether or not to display the form. If the form has been submitted obviously you want to display the results rather than the form, however if it is the first time a user has seen the page you will want to display the form. We do this by checking the method of the page. Either “POST” or “GET”. By default, our page should be set to “GET” unless it has been submitted. What we are going to do is first check to see that the method is not equal to “POST”. If it is “POST” it means that the form has already been submitted and we will instead tell the script to process the form results. It sounds complicated but in reality it isn’t here is all the code we need in order to do this:

<?php
   if ($_SERVER['REQUEST_METHOD'] != 'POST'){
      $my_action = $_SERVER['PHP_SELF'];  

} else {
// process form
}
    ?>

Looking at the code you can see the gist of what we are doing. We have set up an if/else statement. In the “if” part of the statement we are using a predefined server variable $_SERVER and asking to verify that the the “REQUEST_METHOD” of the page is not equal to ‘POST’. By default, pages are set to ‘GET’ so if the form has not been submitted we will then execute a bit of code. That bit of code is where we set the variable $my_action which provides the location of the current page. This will become the value of the “action” attribute in the form we create. The else statement is where we will put the code related to processing the form (once we get there).

Step Two, Create the Form

Next we’ll create a contact form and add it to the script we are building. When we are finished We’ll use this form to send a simple email message to us. In PHP the form works exactly like it does in HTML.

<?php
   if ($_SERVER['REQUEST_METHOD'] != 'POST'){
      $my_action = $_SERVER['PHP_SELF'];
?>

<h2>Contact Us Form</h2>
<form name="Contact_Form" method="post"
               action="<?php echo $my_action;?>">
 Name: <input name="name" type="text"><br>
 Email:<input name="email" type="text"><br>
 Subject:<input name="subject" type="text"><br>
 Message:<textarea name="txt"></textarea><br>
 <input type="submit" value="Send">
</form>

<?php
} else {
// process form
}
    ?>

Notice that we cut into the PHP script to add the form. What we have done is closed out the PHP script at the end of the first “if” statement using the close PHP code ?> We then added the form and re-opened our if/else statement with the open PHP code <?php just after the form. What this does is allow us to open the form if everything checks out in the if statement.

At first glance this form should be near identical to a regular HTML form with one exception. The action attribute has a bit of PHP code in the value:

<?php echo $my_action;?>

What we are doing here is specifying the action value that we placed in the $my_action variable.

Still following me? Good!

Step 3, Process the Form!

Last we need to add the code to process the form if it has been submitted. What we’ll do is check to see that the fields we want filled out are, and if they are we will send the data through the mail() function to mail it out to us and will provide a confirmation screen at the end. I know it is a lot, but I’ve made notes in the code so you can see exactly what happens where:

<?php
   if ($_SERVER['REQUEST_METHOD'] != 'POST'){
      $my_action = $_SERVER['PHP_SELF'];
?>

<h2>Contact Us Form</h2>
<form name="Contact_Form" method="post"
               action="<?php echo $my_action;?>">
 Name: <input name="name" type="text"><br>
 Email:<input name="email" type="text"><br>
 Subject:<input name="subject" type="text"><br>
 Message:<textarea name="txt"></textarea><br>
 <input type="submit" value="Send">
</form>

<?php

} else {

// Check to see that the name is filled out
if (strlen($_POST['name']) > 0) { $name = TRUE; 

   // Check to see if the email is filled out
  if (strlen($_POST['email']) > 0) { $email= TRUE;

	// Check to see if the message is filled out
	if (strlen($_POST['txt']) > 0) { $txt= TRUE;

	// when all looks good go ahead and execute
	echo "<h2>Thanks for the message!</h2>";
	echo "<p>Here is what you submited:</p>";

	//replace the recipient information with your own info
    $recipient = 'info@example.com';
    $subject = stripslashes($_POST['subject']);
    $from = stripslashes($_POST['email']);

	$msg = " Email: ".stripslashes($_POST['email'])."\\n Name:
        ".stripslashes($_POST['name'])."\\n Message: ".stripslashes($_POST['txt']);
    } else {

	// if the message was not filled out
	$txt = FALSE;
    echo "Please fill out all the required fields.";
    } 

  // if the email was not filled out
  } else { $email = FALSE;
  echo "Please fill out all the required fields.";
  } 

// if the name was not filled out
} else {
$name = FALSE;
echo "Please fill out all the required fields.";
}

// when you everything comes back true and you
// get your variables mail it out
if (mail($recipient , $subject, $msg, "From: $email"))

   //nl2br() function inserts HTML line breaks (<br />)
  // in front of each newline (\\n)
   echo nl2br("$msg");  

// if it didn't come back true and you didn't get
// your variables give the message
else
echo "<br />Message failed to send";

}
?>

With everything completed lets go ahead and open the form up in our web browser and see what it looks like. Here is the form. It is ugly but functional:
Mail Form

Once you hit the submit button the mail is sent and you get the confirmation screen:
confirm screen

If you want, you can download the code from this tutorial for free and use it how you like. Here it is. Contact Us Form Code (ZIP)

[ Go back to PHP Tutorial 10 | Using External File Includes in PHP ]

[ Continue to PHP Tutorial 12 | $_GET, $_POST and $_REQUEST variables ]

No Comments | Tags: PHP

PHP Tutorial 10 | Using External File Includes

5 November 2007 - 3:57

Now that you know the basics of PHP we can begin the process of creating an actual website! If you have much experience with HTML you may have heard of Server Side Includes (SSI). Essentially server side includes are a way to create headers, footers, scripting statements, or other elements that can be reused (or included) on multiple pages.

In PHP there are four functions that you can use to call external files and include them in your page. Those are:

include()
include_once()
require()
require_once()

Using Include()

As you can imagine, include() includes an external file in your php script. To demonstrate how this works imagine we have three files.

The first is a header.inc file which contains a basic h1 header for the page:

<h1>Using External File Includes</h1>

The second a footer.inc file containing a paragraph of contact information:

<p>contact us at info@thedesignjunkie.com</p>

You can imagine where we are going with this ;-)

Now, in our PHP file (page1.php) we want to include the header and the footer files. The page code would look something like this:

<html>
<head>
</head>
<body>
     <?php
         include 'header.inc';
     ?>

     <?php
        include 'footer.inc';
     ?>
</body>
</html>

Load all three files to the same directory and call up the PHP page in your web browser and you get:
Include Function

Looking at the source code or the document you’ll notice that you don’t see any PHP script. All you see is the HTML code.

Using Require()

Require() behaves just like include() except if for some reason the file requested does not load the require() function will kill the entire script and you will get an error message. Using include() you don’t get this. For this reason I suggest using include() for cosmetic includes and require() when you have an include that is more important. Essentially, you should use require when you want the entire script to stop if the include is not found.

Include_Once() and Require_Once()

Just like include() and require(), the include_once() and require_once() functions are used to include headers, footers, scripting statements, or other elements that can be reused (or included) on multiple pages. The only difference is that with the ending _once() the functions are only called one time.

[ Go back to PHP Tutorial 11 | Working with Forms in PHP ]

[ Go back to PHP Tutorial 9 | For and While Loops in PHP ]

No Comments | Tags: PHP, Uncategorized

PHP Tutorial 9 | For and While Loops (Looping with PHP)

4 November 2007 - 22:20

Looping is a programing term for running a piece of code several times until a desired outcome is achieved. What you do is set a condition and tell the code that while the condition is true then perform the loop.

In PHP there are a few types of loops that we have at our disposal:

  • The “while” loop, loops through a block of code as long as a specified condition is true.
  • The “do…while” loop, loops through a block of code one time and then repeats the loop
    as long as a special condition is true.
  • The “for” loop, loops through an initial block of code and runs an initial expression. It then checks for a closing expression and runs that. We’ll cover this in more detail below.
  • The “foreach” loop, loops through a block of code for each element in an
    array

The While Loop in PHP

Think of the while loop as a statement that executes a block of code as long as a given condition is true. The syntax goes something like this:

while (expression) statement

The while loop says that while this expression is true, execute this statement. It is important to note that the loop will continue as long as the expression is true so you need to make sure that you put in something that will eventually make the expression false because you don’t want the while loop going forever.

Heres and example of the while loop in action. Let’s say we have a variable called $loop_number with the initial value of 20. We want to create a loop that counts down and outputs the results of that count on screen till we reach a specific number. Here’s what that would look like:

       <?php
            $loop_number = 20;

			while ($loop_number >= 4)

			{
                echo "Count Down Number: ", $loop_number, "<br />";
                $loop_number= $loop_number - (2);
            }
        ?>

Notice that we have made the $loop_number variable count down by two at each loop iteration until it reaches the number 4. We also used the echo() function to output the result of each loop on screen. This results in the following:
While Loop Output

As you can see, the while loop we created counted down by two until it reached the number 4 outputting the results of each loop on screen.

achieved. What you do is set a condition and tell the code that while the condition is true then perform the loop.

In PHP there are a few types of loops that we have at our disposal:

  • The “while” loop, loops through a block of code as long as a specified condition is true.
  • The “do…while” loop, loops through a block of code one time and then repeats the loop
    as long as a special condition is true.
  • The “for” loop, loops through an initial block of code and runs an initial expression. It then checks for a closing expression and runs that. We’ll cover this in more detail below.
  • The “foreach” loop, loops through a block of code for each element in an
    array

The Do…While Loop in PHP

The do…while loop is one of my favorite loops in PHP. It operates in a similar way to the while loop. But, instead of checking to see if a condition is true at the beginning of the loop, it checks the condition at the end of the loop.

Here is an example:

       <?php
            $loop_number = 20;

	    do {
                echo "Count Down Number: ", $loop_number, "<br />";
                $loop_number= $loop_number - (2);
                }

             while ($loop_number >= 4)

        ?>

Notice that our action takes place in the “do” part of the loop. The action is placed inside the curly brackets ({ }). What we have said here is do something while something else is true. In this case count down by two and print it out on screen until the loop number is less than or equal to the number 4. The output looks the same as the while loop we created earlier:

While Loop Output

The do…while loop is useful when you want your script to do something first then test to see if the condition is true rather than test the condition then execute the script.

The For Loop in PHP

The for loop is used when you want to execute a statement a specified number of times. The syntax goes something like this:

for (expression initialization; condition; and increment) statement

There are three parameters that you need to set with the for loop. They are an expression initialization, a condition to be met, and an increment. Here is what it looks like in actual code:

       <?php

           echo "Counting Down to 4! <br />";

	   for ( $loop_number = 20; $loop_number >= 4; $loop_number--)

                {
                 echo  $loop_number, "<br />";
                }

        ?>

Notice that the increment parameter $loop_number– uses the operator “–” to count down (if you wanted to count up you could use “++”). We then used echo() to output the results of that countdown on screen. Here is what it looks like in a browser:

The Foreach Loop in PHP

The foreach loop is used when you want to loop through an array.

<?php

    echo "I have fruits in the following colors: <br />";

    $fruit = array("apples"=>Red, "oranges"=>Orange, "peaches"=>Pink);

     foreach ($fruit as $color)

             {
              echo $color,"<br />";
              }
?>

Notice that I first set an associative array giving each type of fruit a key that had a value of a specific color. Then I used the foreach loop to look at each piece of fruit and return the color value. The echo() function is what I used to print it out on screen. The output of this script looks like this:
Foreach Loop Output
[ Go back to PHP Tutorial 8 | PHP’s Built-in Functions ]

No Comments | Tags: PHP

PHP Tutorial 8 | Built-in Functions

4 November 2007 - 20:28

At this point you are already aware that functions exist and that we can use them to tell PHP to do things. But up to this moment we have not spent much time looking at the types of functions that exist in PHP.

In PHP functions come in two forms: Built-in, and User Defined. Built-in functions, as you can imagine, are built into PHP and may change depending on which version of PHP you are using. That is why some scripts built in PHP 5 are not supported on servers that are running PHP 4.

For your reference, PHP.net publishes a complete online reference containing all of the built in functions that PHP has to offer. You can find it here: http://www.php.net/quickref.php

For our purposes, lets look at a few of the most common built in functions, show you how to use each, and introduce you to the language used by us web geeks to describe what is happening.

strlen()

One of the most common built in functions in PHP is the strlen() function which we briefly covered earlier. This function returns the length of a particular string. Here is an example of how it can be used:

<?php
$number_count = strlen(”How Many Characters?”);
echo $number_count;
?>

Notice that we followed a particular syntax. We set a variable equal to something with the equals sign (=). On the left side of the equals sign we created a variable $number_count. On the right of the equals sign we called the function strlen(). Inside the function is the string of text that is being analyzed. The code above outputs the following result:

20

Essentially we followed this syntax:

$some_variable = call_function_name ( [ insert_parameters] );

Okay, strlen() is easy because it simply counts things. It has only one real parameter. Many of the built in functions have many parameters.

mail()

This is probably one of the most useful functions to newbies because learning how to use it means that you can enable your site to email information based on user inputs. It is essential for things like a “contact us” form on your website.

The mail() function follows a particular syntax:

mail(to,subject,message,headers)

This means you need to insert a value for each parameter you wish to use: To, Subject, Message, Headers

The most common way to do this is to pass the values to the function using a variable like this:

<?php

     $to = "someemail@someemail.com";
     $subject = "Nice Subject Line";
     $message = "This is a very short message. Enjoy!";
     $headers = "From: someotheremail@someemail.com";

     mail($to,$subject,$message,$headers);

?>

Notice that this function followed the following syntax:

call_function_name ( [ insert_parameters] );

strip_tags()

The strip_tags() function is designed to strip all of the HTML and PHP tags from a value. As you can imagine, it is very useful when people are submitting information via a submission form.

The strip_tags() function follows a particular syntax:

strip_tags($text_to_strip, allowable_tags)

Looking at the above we first have the function, a parenthesis, the text we want to strip (in a variable), and then we include the tags we want to allow. Here is an example using the strip_tags function:

<?php

$text_to_strip = "<h2>Strip Tags</h2><p>Takes out the paragraph tags</p<p>and leaves the heading tags.</p>";

// echo is needed to print strip_tags() on screen

echo strip_tags($text_to_strip, "<h2>");

?>

Notice that I added echo() in order to output the strip_tags() function. Looking at this code in a browser we get the following:

Strip Tags

Takes out the paragraph tags and leaves the heading tag.

[ Continue to PHP Tutorial 9 | For and While Loops in PHP ]
[ Go back to PHP Tutorial 7 | Working with Arrays in PHP ]

1 Comment | Tags: PHP

PHP Tutorial 7 | Working with Arrays

29 October 2007 - 9:01

Arrays are a way of storing multiple values in one variable. In essence it is a way of storing separate pieces of information (either strings or numbers) in one variable. I think of it like a shopping list. For example my shopping list contains apples, oranges and peaches. In this example I can set a variable for my shopping list ($shlst) and set build an array out of my fruit.

Arrays function by assigning a key to each value in the array. In other words, each element in the array has its own ID allowing it to be accessed appropriately.

There are three types of arrays:

  • A Numeric array - An array with a numeric ID key
  • An Associative array - An array where each ID key is associated with a value
  • And, a Multidimensional array - An array containing one or more arrays

Numeric Arrays

Going back to our shoping list variable ($shlst), lets go ahead and build a Numeric array. Well start by putting apples in our array. We’ll start by creating an array out of our apples, oranges and pears:

$shlst[0] = “Apples”;
$shlst[1] = “Oranges”;
$shlst[2] = “Peaches”;

Notice that all we did was set a variable: $shlst
assign a numerical key: [0]
and then set our value: =”apples”;

If I wanted to put that in array into a php script and have it output code I would simply do the following:

<?php
     $shlst[0] = "Apples";
     $shlst[1] = "Oranges";
     $shlst[2] = "Peaches";

echo "Shopping List: ".$shlst[2]." ".$shlst[0]." and ".$shlst[1]."'s";
?>

The code above will give me the following output:

Shopping List: Peaches Apples and Oranges’s

In this code we have set the numeric key manually, but it is also possible to have the key automatically assigned. To do that we would simply write the array like this:

$shlst = “Apples”, “Oranges”, “Peaches”;

Notice that in this example there is no key []. That is because it is being auto assigned and you are not setting it manually. Also notice that each piece of fruit is surrounded by its own quotes and separated by a comma.

Associative Arrays

Associative arrays allow you to associate values to a name instead of using a numeric key. It is very useful because it allows you to freely associate values that relate to each other. For example lets say we have red apples, orange oranges, and pink peaches (i know they are more orange but hey, I wanted a different color).

Let’s put these things into an array so that you can see what I am talking about.

$fruit = array("Apples"=>Red, "Oranges"=>Orange, "Peaches"=>Pink);

What we have done here is assign created an array of fruit with colors associated to each piece. If we wanted to write it in code we could do the following:

<?php
$fruit = array("apples"=>Red, "oranges"=>Orange, "peaches"=>Pink);

echo "<p>Q. What color are apples? A.".$fruit['apples']."</p>";
echo "<p>Q. What color are oranges? A.".$fruit['oranges']."</p>";
echo "<p>Q. What color are peaches? A.".$fruit['peaches']."</p>";
?>

Looking at what we have done notice that we assigned the color red to “apples” and the color orange to “oranges” and finally the color pink to “peaches”.

Mulidimensional Arrays

Multidimensional arrays are a very powerful feature of PHP. In essence, each variable or element in the main array can also be a variable or element. This allows you great flexibility. For example if you had an $apple_type array you could break that up into arrays based on an $apple_color array which then linked apple colors to their exact names.

Let’s look at how that would work. Note that in the code below I chose to create an array that automatically assigns ID keys:

<?php
$apple_type = array
  ( 

      "Green_Apples"=>
               array ( "Granny Smith" , "Golden Delicious"),

      "Red_Apples"=>
               array ( "Washington Apple" , "Paula Red")

   );

     echo "A " . $apple_type['Green_Apples'][0] .
            " is definitely not a red apple like a ".
            $apple_type['Red_Apples'][1].
            ".";

?>

Notice that we first created an array for $apple_type which we filled with two arrays for $Green_Apples and $Red_Apples. On outputting the results with the echo command we use the $apple_type[’Green_Apples’][0] to call up the final value of Granny Smith and $apple_type[’Red_Apples’][1] to call up the value Paula Red. It is important to note that the automatic key values start with zero rather than one. So, when calling up values you must take into account zero [0] as a placeholder.

The code above yields the following result:

A Granny Smith is definitely not a red apple like a PaulaRed.

[ Contunue to PHP Tutorial 8 | PHP’s Bulit in Functions ]

[ Go back to PHP Tutorial 6 | Switch Statement in PHP ]

No Comments | Tags: PHP

PHP Tutorial 6 | Switch Statements

29 October 2007 - 8:59

In PHP Tutorial 5 we discussed if -> elseif -> else statements. There is however, one more common type of conditional statement called the Switch Statement.

A Switch statement is generally used when you have a series of conditional statements and want to do comparisons quickly while cutting down on the amount of code needed for the program to make a decision.

Here is how it works. The Switch first evaluates a variable and compares it to what is called a Case. Here is an example:

    <?php

       $apple_color = Red;

       switch ($apple_color) {

       case 'Green':
               echo "Granny Smith!";
               break;

      case 'Red':
              echo "This apple is from Washington!";
              break;

      case 'Yellow':
              echo "This is not the best apple.";
              break;

     default:
            echo "No apples by color.";
      }
   ?>

A point of note is that Switch statements are more limited than if/elseif/else statements because they can only check to see if one variable is equal to another.

Notice that in the code above we are evaluating a single expression. In this example that expression is the $apple_color variable. The statement then compares that variable to each of the cases listed in an attempt to find a match. After each case, we have inserted a BREAK to cause the code to stop. This prevents the code from going on to the next case once it has found it’s match. However, if the program runs through each case and doesn’t find a match it will finish by outputting the default statement.

[ Continue to PHP Tutorial 7 | Working with Arrays in PHP ]

[ Go Back to PHP Tutorial 5 | Conditional If/Else Statements and Operators in PHP ]

No Comments | Tags: PHP

PHP Tutorial 5 | Conditional Statemens (If -> Else) and Operators

29 October 2007 - 8:58

Conditional statements are a way of saying, “hey, if the following criteria is met, then do this”. In PHP this happens through through two types of statements “If/Else Statements” and “ElseIf Statements”.

condition is true, execute this code;

elseif (condition)
next elseif condition is true, execute this code;

else
condition is false, execute this code;

Now, let’s use this in an example. Let’s imagine we have two colors of apples: red, and green. We want to set a variable for a color and then do a series of If/Elseif/Else statements to return the type of apple it is.

<?php
$color = "Red";

  if ($color == "Green")

        echo "This is a Granny Smith"; 

  elseif ($Color == "Red")

        echo "This is from Washington!"; 

  else

        echo "This isn't an apple!";
?>

As you can see the $color variable is set to “Red”. I used what is known as a comparative operator “==” to examine whether or not the statement was true or not. In this case if $color is equal to green (if ($color == “Green”)) we get the answer “This is Granny Smith!” returned. If $color is equal to red ((elseif ($color == “red”)) we get “This is from Washington!”.

As a result of our code we know that the $color variable is equal to red so, as a result we get the following:

This is from Washington!

If we set the color variable to “Green” we get:

This is a Granny Smith!

And, if we set it to “Blue” or some other color we would not get a match and would end up with:

This is not an apple!

Okay, so now that you have an idea of how If/ElseIf/Else Statements work lets examine the various types of operators that are available for you to use.

PHP Operators

We’ve saw the Arithmetic operators in the last tutorial. So you should be somewhat familiar with how they are used in the code. In addition to arithmetic operators, there are also operators related to Assignment of values to variables, Comparison of one value or variable to another, and last there are operators that allow you to perform logical tasks. Below is a reference:

Common Arithmetic Operators

Operator Description Example Result
+ Addition $a + $b The sum of $a and $b. So, if a equals 2 and b equals 3 the result would be 5.
- Subtraction $a - $b The difference of $a minus $b. So, if a equals 3 and b equals 2 the difference is 1.
* Multiplication $a * $b $a multiplied by $b. So, if a is 2 and b is one the product is equal to 2.
/ Division $a / $b $a divided by $b. So if a is 6 and b is equal to 2 the quotent is 3.
% Modulus (division remainder) $a % $b Remainder of $a divided by $b
- Negation -$a The opposite of $a
++ Increment $a ++ Kina like counting. If $a is equal to 4, the next increment is 5.
Decrement $a – Kina like counting. If $a is equal to 4, the next decrement is 3.

Common Assignment Operators

Operator Description Example Result
= Is set to $a = $b So, $a is equal to $b. But a better way to think of this is that what is on the left gets set to what is on the right.
+= Plus Equals $a += 6 This says
to to value on the left, "add the value on the right of yourself and then set yourself to that value". In other words if $a is 3 it adds 6 to output 9. Then it says hey, now $a is set to that number instead. So $a is now equal to 9."
-= Minus Equals $a -= 2 This says to to value on the left, "minus the value on the right of yourself and then set yourself to that value". In other words if $a is 3 it subtracts 2 to output 1. Then it says, "hey, now $a is set to that number instead. So $a is now equal to 1."

Common Comparison Operators

Operator Description Example Result
== is equal to $a == $b If we set $a to 3 and $b to 3 the result would be TRUE
!= is not
equal
$a != $b If we set
$a to 3 and $b to 3 the result would be FALSE
> is greater than $a > $b If we set
$a to 3 and $b to 1 the result would be TRUE
< is less than $a < $b If we set
$a to 3 and $b to 1 the result would be FALSE
>= is greater than or equal to $a >= $b If we set
$a to 3 and $b to 1 the result would be TRUE
<= is less than or equal to $a <= $b If we set
$a to 3 and $b to 1 the result would be FALSE

Common Logical Operators

Operator Description Example Result
&& and $a < 9
&& $b > 2
If we set $a to 4 and $b to 5 the result would be TRUE
|| or $a==3 ||
$b==3
If we set $a to 4 and $b to 5 the result would be FALSE
! not !( $a == $b ) If we set $a to 4 and $b to 5 the result would be TRUE

[ Continue on to PHP Tutorial 6 | Switch Statements in PHP ]

[ Go back to PHP Tutorial 4 | Working with Numbers and Arithmetic Operators in PHP ]

No Comments | Tags: PHP

PHP Tutorial 4 | Working With Numbers and Arithmetic Operators

29 October 2007 - 8:57

Number type variables are similar to String type variables in that whatever variable you set is equal to something. For example the variable $my_number can be equal to some number. Lets say 7. The code for such a scenario would look like this:

<?php
$my_number = 7;
?>

Notice that there is one major difference between working with numbers and working with strings. When working with numbers you do not place quotes around the value. If you did decide to place quotes around the value (in this case, the number 7), you would no longer have a number type variable. Instead, you would have a string type variable. In other words your computer would not interpret the number as a number, it would interpret it as a word (or string of text characters).

Arithmetic Operators

Now, lets do some math. In PHP, just like your elementary math courses, you can add, subtract, multiply, and divide. The opperators for these are:

+        Addition
-        Subtraction
*        Multiplication
/         Division

In addition there are a few other cool opperators that you may not know:

%       Modulus
++      Increment
--       Decrement

The Modulus operation finds the remainder of division of one number by another (wikipedia has a great explanation of how it can be used). Look at the following example:

<?php

$my_number = 7;
echo ($my_number)%2;

?>

Notice that I’ve entered a value or 7 for the variable $my_number and then said modulo by 2. Because the Modulus operator gives the remainder of the division 7 by 2 the answer is:

1

Now, if you change it to 7%5 the answer would be 2. Got it? good.

Increment and decrement operators are also very useful and work in a similar way. For example lets look at the following:

<?php
$my_number = 7;
echo ($my_number)++;

?>

In this case I’m setting $my_number variable to the number 7 and asking it to go up by an increment. Essentially I am saying count up one. The output for this is:

8

Built-in Mathematical Functions

PHP also has a number of built in functions to make your life easier when working with numbers. The most common of which is the round() function.

Here is an example:

<?php
$my_number = 2.453;
echo(round ($my_number));
?>

As you can see, in this example I am rounding off the number. The result is:

2

You can also use this function to round to a specific decimal place. lets say we want to round to two decimal places out. In that case we would use the following code:

<?php
$my_number = 2.453;
echo(round ($my_number, 2));
?>

Notice I added a comma, a space, and the number 2 after the variable $my_number inside the round function. This will yield the following output:

2.45

another couple cool mathematical function the min() and the max() functions. The min() function takes two numbers, compares them and outputs the lower of the two. The max() function takes two numbers, compares them and then outputs the higher of the two. Lets take 5 and 7 for example. Using the max() function, the code would look something like this:

<?php
$my_high_number = 7;
$my_low_number = 5;
echo(max ($my_high_number,$my_low_number));
?>

Notice I set two variables for my numbers. One is a high number, and the other is a low number. They are equal to 7 and 5. As you can imagine, using the max() function the code returns the higher value of the two generating the following result:

7

The last function that I’m going to show you isn’t really mathematical, but it is most appropriate that you learn it here. The function is the number_format() function. The cool thing about this function is that it takes a number, like 1967 and styles it. So the number 1967 comes out like 1,967. In essence, it groups the numbers and puts a comma where it needs to be. Here is an example:

<?php
$my_number = 1967;
echo(number_format ($my_number));
?>

Notice that I didn’t put a comma in my number. Yet it comes out like this:

1,967

[ Continue to PHP Tutorial 5 | Conditionals in PHP ]

[ Go back to PHP Tutorial 3 | working with Strings and Numbers in PHP ]

No Comments | Tags: PHP

PHP Tutorial 3 | Working With Strings

29 October 2007 - 8:56

In the PHP Tutorial 2 | PHP Variables we covered the basics of what variables are. In doing so we also introduced strings.

What are strings?

Strings are simply a grouping of characters that PHP relates to a variable. This grouping can be a bunch of letters like “ABCDE” or it can be a word like “Hello” or it can be a combination of numbers and letters and other types of punctuation like “tutorial_3 on PHP”.

To demonstrate lets assign the strings “Granny Smith” and “Green” to the variables $apple_type and $color:

$apple_type = ‘Granny Smith’;
$color = ‘Green’;

Putting them into our PHP script along with the echo () function, would look like this:

     <?php

        $apple_type = 'Granny Smith';
        $color = 'Green';

        echo $apple_type;
        echo $color;
      ?>

Notice that we placed “echo $apple_type;” and “echo $color;” on separate lines. Looking at our file through a web browser we’ll see that even though they are on separate lines the print one right after the other:

Granny SmithGreen

A better way to write this code is to concatenate the strings and add the formatting we need at the same time.

Concatenating Strings

Concatenating strings is performed using the period (.)

In our code, to concatenate the two variables we simply place the period in between the variables we want to concatenate. Here’s an example:

<?php

$apple_type = ‘Granny Smith’;
$color = ‘Green’;

echo $apple_type.$color;
?>

This will result in the following to be printed on screen:

Granny SmithGreen

As you can see we still need to add some additional formatting. And, by concatenating some formatting into things we can. Here’s how:

<?php

$apple_type = ‘Granny Smith’;
$color = ‘Green’;

echo $apple_type.’ ’.$color;
?>

Notice that I added ‘ ’ to the code will result in the following:

Granny Smith Green

String Specific Functions

In PHP, there are several functions that you should be familiar with. I’ll cover just a few here to give you an idea of some of the built in possibilities.

strlen() — counts how many characters your string contains. Here is an example Lets count how many characters we have in the $apple_type string we created above. Here’s how that looks:

<?php

$apple_type = ‘Granny Smith’;
$color = ‘Green’;

echo strlen ($apple_type);
?>

Looking at the results we get:

12

Another useful one is chunk_split(). As the name implies, this function splits a string into a number of smaller chunks. The syntax is as follows: chunk_split(string,length,end)

Here’s an example of how it works:

<?php
$apple_type = “Granny Smith”;
echo chunk_split($apple_type,1,”-”);
?>

Notice that we split the words Granny Smith ($apple_type) at a specific interval (1), and we told the function to end each split with a dash (”-”). Here is what the output looks like:

G-r-a-n-n-y- -S-m-i-t-h-

The last one we’ll cover in this section is str_replace(). This function simply replaces part of a string with something else. It follows a specific syntax:
str_replace(find,replace,string,count)

Here is an example of how it works:

<?php
$apples =”Granny Smith apples are red.”
echo str_replace(”red”,”green”,$apples);
?>

Notice that I created a string “Granny Smith apples are red.” Using str_replace() I am able to replace the word red with the word green giving me the following result:

Granny Smith apples are green.

[ Continue to PHP Tutorial 4 | Working With Numbers and Arithmetic Operators in PHP ]

[ Go back to PHP Tutorial 2 | Variables in PHP ]

No Comments | Tags: PHP