Now that you have a working PHP development environment, it's

advertisement
Now that you have a working PHP development environment, it's time to start
learning some of the actual language.
In the next few articles, we will be taking a look at the fundamentals of the PHP
language in preparation for creating your first script: a full-fledged form
processor. This time, we will be focusing on the basic structure of PHP and
taking a look at how it handles variables and data types.
Basic Syntax
Starting and Ending PHP Code Blocks
Take a look at the following simple PHP script:
<html>
<head>
<title>Testing PHP</title></head>
<body>
<?php print "hello there!"; ?>
</body>
</html>
In this example, PHP is embedded directly into an HTML document. Because
PHP and HTML can be mixed like this, every block of PHP code must be
surrounded by Start and End elements. These elements allow PHP to see which
sections of the page need to be parsed, and which can be ignored.
PHP recognizes four different versions of these sets:
1. <?php print "hello there!";?>
2. <script language="php"> print "hello
there!";</script>
3. <? print "hello there!"; ?>
4. <% print "hello there!"; %>
The first two versions are supported by PHP by default; however, you will rarely
see the second used in any scripts. Shorter and easier to remember, the first is
the preferred usage. The third method is also frequently used, but requires the
"short_tags" option to be enabled in the PHP configuration file. Although many
web hosts do enable this option, keep in mind that any scripts written using them
may not work in certain situations. The final method will look familiar to ASP
developers. Known as ASP Style tags, this is the least-used method and requires
the "asp_style" option to be enabled.
You have also probably already noticed that most lines of PHP code end with a
semi-colon. The semi-colon tells PHP when one statement is finished, so it can
go on to evaluating the next. A closing PHP tag right after a statement has the
same effect as a semi-colon:
<?php print "hello there!" ?>
Comments
Just like in HTML, PHP allows you to comment out lines of text. There are
three ways to do this:
1. // This comments out a single line.
2. print "Hi there"; #this is also a single line
comment.
3. /* This is used to comment
out multiple lines */
Commenting your script can become vital, especially when working on larger
projects and its a habit that you should develop now. Including information
about which blocks of code perform which functions can be a life saver if you
return to a project after you have forgotten the details. If you are working on a
collaborative project, having a well-documented script also makes it easy for
other people to understand script logic and your thought process.
PHP Building Blocks - Variables
If you have ever sat through a basic algebra class, you are probably already
more familiar than you realize with what variables do and how to work with
them.
Just as in math, variables in PHP are containers for bits and pieces of data. They
are denoted by a dollar sign, and can be named anything beginning with a letter
or underscore. Variable names can only contain letters, numbers, or underscores
and are always case sensitive.
As a quick sample, try running the following script on your server:
<html>
<body>
<?php
$var = "Hello there!";
print $var;
?>
</body>
</html>
When you run it, you will see that it prints "Hello there!" in your browser.
Looking at the script, this makes sense: We begin by creating a variable called
$var and assign a string value of "Hello there!" to it using the assignment
operator (=). In the next line of the script, we use a print command to output the
value of $var.
If you are making the leap to PHP after working with another programming
language such as C, keep in mind that you do not need to declare your variables
before using them. A variable in PHP is created automatically as soon as a value
is assigned to it.
Now, take a look at the following script:
<html>
<body>
<?php
$var1 = 1;
$var2 = 4;
$sum = $var1 + $var2;
print "The result of $var1 + $var2 is $sum";
?>
</body>
</html>
Run this script and take a look at the output. Just like in the previous script, we
created a variable. This time, we assigned a number to it instead of some words,
and created a second variable as well. In the 3rd line, we added them together
and assigned the sum to a variable called $sum. Because $var1 and $var2 are
numbers, any mathematical operation can be applied to them, not just addition.
If you compare the two scripts, you will notice some slight differences in how
the variables were assigned and in the way data was outputted to the browser. In
the first script, the sentence assigned to the variable was surrounded by
quotation marks, and the variable outputted to the browser was not. In the
second, the exact reverse was the case.
Wondering why? Part of the answer lies with how PHP handles different types
of data.
PHP Building Blocks - Data Types
In PHP, every piece of data assigned to a variable is of one type or another. The
types that PHP currently support are: Strings, Arrays, Integers, Floating Point
Numbers, and Objects. For now, we'll just take a look at Strings and Integers,
since both were used in the last two test scripts.
Strings
In PHP, a String is simply defined as a series of characters. They can contain
letters, ASCII characters, numbers, and even other variables.
When you assign a string to a variable or print it out to the browser, you must
demark where that string begins and ends. Two of the most common ways of
doing this are:
1. Single Quotes:
$var = 'Hi there';
print 'Hi there';
2. Double Quotes:
$var = "Hi there";
print "Hi there";
Though the two methods resemble each other closely, there are slight
differences in how they work. Try the following script:
<?php
$var = "This is a";
print "$var test<br>";
print '$var test';
?>
Based on what you know of PHP, you might expect that both lines would return
"This is a test". But take a look at the output:
This is a test
$var test
The major difference between double and single quotes is that contents within
single quotes are taken literally. If you have any variables within them, they will
not be translated into their values. This, however, will work:
print $var . ' test';
Since only strings need to be surrounded by quotes to be printed out, this is
perfectly valid. Called the concatenation operator, the period works to append
the right argument to the left, "gluing" them together and printing them both out.
In many instances, you may wish to print or assign a string which contains
quotation marks. When you do, if the quotation mark is the same as the ones you
are using to demark the string, it must be escaped by using a backslash.
Escaping a character lets PHP know that you wanted it to be interpreted literally.
For example:
$var = "I'm a string"; -- this is acceptable
because you are using a single quotation mark
within double ones. No escape character is needed
here.
$var = 'I'm a string'; -- This would give an
error because PHP sees the second single
quotation mark as the end of the string, and the
rest of the text following it as garbage that it
can't understand.
$var = "I\'m a string"; -- This is the correct
way to escape a quotation mark.
Integers
Just as in math, whole numbers, negative or positive, and zero are considered
Integers. When you assign an integer to a variable, you do not use quotation
marks:
$var = 1; -- this is an integer
$var = 0; -- this is an integer
$var = "1"; -- this is a string.
Type Juggling
One of things that make PHP so easy to use is its flexibility in how it handles
types.
When you create a new variable, PHP automatically determines what type that
variable is based on the data that you assigned to it. So, if you assign a string to
a variable, the variable becomes a string. Likewise, assigning a function or an
integer to a variable would cause the variable to become the associated type.
After creation, a variable can also change types on the fly based on what context
it is used in:
$var = "1"; -- $var is a string.
$var= $var + 1; -- $var is increased by one, and
becomes an integer.
In the above example, $var was converted from a string to an integer because a
numerical operation was performed on it. This is known as String Conversion.
If a string begins with numbers and also includes text, PHP will use the
beginning set of numbers and completely ignore the rest of the text. If the string
had not begun with a number, then PHP would have assumed $var was equal to
0 for the purposes of performing the operation. The end value of $var would
have been one, instead of two.
If you want to see how this works in action, try running following script:
<?php
$var = "1";
$var=$var + 1;
print "$var<br>";
$var = "123 Texttexttext";
$var = $var +1;
print "$var<br>";
$var = "Hi there!";
$var = $var +1;
print $var;
?>
In the above script, the string variables were changed to integer variables
because an integer value was added, but that is not always the way it works:
$var = "33";
$newvariable = $var + 1;
$newvariable is an integer, but $var remains a string because the result of the
operation was assigned to a new variable. Even though the original variable
remains the same type, this is still considered String Conversion.
In a process known as Type Casting, you can force PHP to treat a variable as
one type or another when you create it:
$var = (int) "4"; -- $var is a int even though
its surrounded by quotes, because you have
defined it as such.
You can also specifically change the type of it is after having created it by using
the settype() function:
$var = (int) "4";
$var = settype($var, float); -- $var becomes a
float.
Keep in mind that while there are some occasions where you may need to
manually set or change the type of a variable, PHP is very accurate in dealing
with them in the proper context and typically you should let it do the work.
If you are feeling a little confused, don't worry. Generally, much of this takes
place behind the scenes. As you work more with PHP, you will gain a better feel
for how types come into play and how to work with them.
By now, you should have a good feel for the basic syntax of PHP, and an
understanding of how to work with variables. In this article, you have run into a
few instances where various operators have been used: the assignment operator
to give a variable a value, the addition operator to add two values together, and
the concatenation operator. Next time, we will be taking an in-depth look at
more of the operators commonly used in PHP. Stay Tuned!
Things to Remember:

Every PHP code block needs to begin with an opening
PHP element and end with one.

Statements in PHP must end with a semi-colon. This
defines the end of an instruction.

A variable is created by assigning a value to it.
Variables are denoted with $, must begin with a letter
or an underscore, and can contain any combination of
letters, numbers or underscores.




other
PHP has 5 different Types: Strings, Arrays, Integers,
Floating Point Numbers, and Objects.
Strings begin and end with either double or single
quotes. Only strings need to be surrounded by quotes
to assign them to variables or print them out.
When using quotes to define a string, quotes of the
same type within the string must be escaped with \.
PHP plays fast and loose with types. You do not need
to define what type a variable is when you create it
and the type of a variable can also change after the
variable has been created depending on the context it
is used in.
To effectively use a programming language you must perform operations. In Liz
Fulghrm's continuing series on programming PHP, she presents coverage of this
language's operators.
Operators are one of the most essential components of PHP; in fact, there is little
you can do without them. They are used to assign variables, work with strings,
and work with numbers. They are also integral in controlling program flow, as
you will later learn.
In this article, we will be exploring some of the most common operators used in
PHP, and how to use them.
So what exactly are operators? Well, to briefly define them, an operator is any
symbol used to perform an operation on a value. The actual symbol used to
perform the operation is known as an operand. In PHP, operators can easily be
grouped by function.
The Assignment Operator
This is the most common operator you will run across in the course of
programming PHP. As introduced in the last article, the assignment operator
allows you to assign a value to a variable. You can assign strings, integers, even
the results of functions:
$var = "Hi there";
$var = 1;
$var = myfunction();
The Concatenation Operator
This operator allows you to append one value to another. You can append
strings, other variables or even the results of functions:
$var = "test";
$var2 = "This is a ".$var;
print $var2; -- This would output "This is a test"
You can also use what s called the Assignment Concatenation Operator to
append a new value to the value an existing variable:
$var = "this is a test";
$var .=" of the emergency broadcast system";
print $var; -- This would output "This is a test of the
emergency broadcast system"
This ability can be especially useful, as we will explore a little later on.
Arithmetic Operators
Just like in math, Arithmetic Operators in PHP are used to work with numbers.
Addition subtraction, division and multiplication are all supported:
Operand Name
Sample
Description
+
Addition
$var + $var2
Adds the two
values together
-
Subtraction
$var - $var2
Subtracts the
second value
from the first.
*
Multiplication
$var * $var2
Multiplies the
two values by
each other.
/
Division
$var/$var2
Divides the
first value by
the second.
$var%$var2
Returns the
remainder of the
first value
divided by the
second.
%
Modulus
The first four will seem very familiar to you. They are the same operators you
have been using since elementary math, and they work the same way. The
Modulus operator is a little more obscure, but can be invaluable. We will
explore how it works in the context of an actual script later on.
Incrementing/Decrementing Operators
PHP supports specific operators for incrementing and decrementing numbers.
These are a short hand way of expressing the increase or decrease of a value by
one:
Operand Name
Sample
Description
++
Postincrement
$var++;
Returns $var, then
increases it by 1.
++
Preincrement
++$var;
Increases $var by 1,
then returns it.
--
Postdecrement
$var--;
Returns $var, then
decreases it by 1.
--
Predecrement
--$var;
Decreases $var by 1,
the returns it.
Samples:
$x = 1;
$x++; $x would have the value of 2
$x = 4;
print --$x; -- 4 would be outputted, and then $x would
be decremented.
Comparison Operators
Frequently in PHP you will find the need to evaluate the relationship between
one value and another. Comparison Operators allow you to test things like
whether one number value is larger, smaller or equal to another. Unlike
expressions with Arithmetic Operators (which return a value), those with
Comparison Operators evaluate to either TRUE or FALSE and are frequently
used in conditional statements:
Operand Name
Sample
Description
==
Equal to
$var ==
$var2
Is true if the first
value is equivalent to
the second.
!=
Not equal to
$var !=
$var2
Is true if the first
value is not equal to
the second.
<
Less than
$var <
$var2
Is true if the first
value is less than the
second.
>
Greater than
$var >
$var2
Is true if the first
value is greater than
the second.
<=
Less than or
equal
$var <=
$var2
Is true if the first
value is less than or
equal to the second.
>=
Greater than
or equal
$var >=
$var2
Is true if the first
value is greater than
or equal to the second.
The Equal and Not-Equal To operators are also used to evaluate whether nonnumerical values are equal to each other. As an example, imagine a situation
where you were developing a user login system and needed to see if the
password the user entered was the same as what you had stored.
Try this script on your server to see how you can use a conditional statement to
test whether or not the entered password is the same as the stored one:
<?php
$storedpassword = "mypassword";
$enteredpassword = "mypassword";
if ($storedpassword == $enteredpassword) {
print "The entered password was correct!";
}else {
print "The entered password was wrong!";
}
?>
To express it in pseudo-code: "If the stored password is equal to the entered
password, the passwords match and The entered password was correct! is
printed. Otherwise, the two passwords do not match and the entered password
was wrong! is printed."
You could also reverse the logic for the same effect:
<?php
$storedpassword = "mypassword";
$enteredpassword = "mypassword";
if ($storedpassword != $enteredpassword) {
print "The entered password was wrong!";
}else {
print "The entered password was correct!";
}
?>
As you might have guessed, the match is case sensitive; "mypassword" is not the
same as "Mypassword". Try substituting different values for $enteredpassword
to see how the script behaves when the two passwords are not the same.
In addition to the comparision operators listed above, PHP4 has added two new
ones that not only allow you see if two values are equal, but also check to see if
they are of the same type. These are identical to their cousins, except they use an
additional equal sign:
Operand Name
Sample
===
Identical
$var ===
$var2
!==
Not
identical
to
$var !==
$var2
Description
Is true if the first
value is equivalent to
the second and both
are the same type.
Is true if the first
value is not equal to
the second or they are
not the same type
Logical Operators
So what happens if you want to evaluate whether more than one condition is true
or false? Going back to the example of the user login, pretend you wanted to
check to make sure the user's username and password matched the stored ones.
You could easily do something like this:
<?php
$storedusername = "user";
$enteredusername = "user";
$storedpassword = "mypassword";
$enteredpassword = "mypassword";
if ($storedusername == $enteredusername AND
$storedpassword == $enteredpassword) {
print "The entered username and password were
correct!";
} else {
print "The entered username and password were
wrong!";
}
?>
The "AND" between the two separate conditions tells the script that both must
be true for the entire statement to be considered true. If both are true, then "The
entered username and password were correct!" would be printed.
PHP supports several different Logical Operators:
Operand Name
AND
OR
And
Or
Sample
Description
$var AND
$var2
Is true if both values are
true.
$var OR
$var2
Is true if either value is
true.
XOR
Xor
$var XOR
$var2
Is true if either value is
true, but not both.
&&
And
$var &&
$var2
Is true if both values are
true.
||
Or
$var ||
$var2
Is true if either value is
true.
!
Not
!$var
Is true if the value is not
true (ex. if the variable
doesn t exist).
After looking at this chart, you are probably wonder why there are two different
operators for AND and OR. Part of the answer lies with Operator Precedence.
Operator Precedence
Take a look at the following:
$x = 9 + 1 * 10
Because we read left to right, you might assume that $x equals 100 (Nine plus
one, times 10, equals 100); however, because of operator precedence, you would
be wrong. The multiplication operator has higher precedence than the addition
operator, so that calculation would be performed first: One times 10, plus nine,
equals 19.
The same rules of precedence apply to Operators in PHP. Take a look at the
below chart to get an idea of how various operators rank. Operators listed in the
same row have equal precedence.
Highest Precedence
* / %
+ - .
< <= > >=
&&
||
And
Xor
Lowest precedence
or
You can also force precedence by using parentheses:
$x = (9 + 1) * 10
Since the first part of the above equation is surrounded, it would be calculated
first, and $x would equal 100.
Finally...
In this article, I have touched on some of those most common operators used in
PHP. There are others that you will discover as you progress in learning the
language, including some that will be introduced later in this series.
In the next article, we will take a look at conditional loops and control
structures, leaning heavily on the concepts introduced here. Stay tuned!
OTHER
Have you ever stopped to give directions to a lost driver from two states away? For the
sake of providing an example, imagine your conversation went something like this:
"Hi, can you tell me how to get to route 50?"
"Sure, just follow this road, turn left onto the expressway, keep driving, and eventually
you'll see the exit for route 50."
The directions above were linear and sequential: drive on this road, turn here, and then
drive until you see the exit.
Obviously, they are horrible directions.
They don't tell the driver how long to drive on the road before they reach the expressway
or that they might want to take a different route to avoid traffic if they tried to leave
during rush hour.
If you wanted to give more exact and useful directions, you might say something like:
"Sure, just follow this road for two miles. If its not rush hour, you can take a left at the
lights onto the expressway and follow it for another mile until you see the exit for route
50. If you hit it near rush hour, you'll want to avoid the expressway and just follow the
road for another 5 miles to route 50."
Without Control Structures, PHP would be much like the first set of directions: linear,
sequential, and not overly useful.
Control Structures are at the core of programming logic. They allow a script to react
differently depending on what has already occurred, or based on user input, and allow the
graceful handling of repetitive tasks.
In PHP, there are two primary types of Control Structures: Conditional Statements and
Control Loops. In the last article, you saw some brief examples of Control Structures.
This time, we will be taking a closer look at them.
Conditional Statements
Conditional Statements allow you to branch the path of execution in a script based on
whether a single, or multiple conditions, evaluate to true or false. Put simply, they let you
test things and perform various actions based on the results.
If Statements
Take a look at the following:
<?php
$x=1;
if ($x == 1) print '$x is equal to 1';
?>
This example illustrates the simplest kind of If Statement. If Statements always begin
with "if", followed by a condition surrounded in parentheses. If the condition evaluates to
true, then the statement or statements immediately following the condition will be
executed. In this case, had the condition been false, nothing would have occurred and you
would have seen a blank browser window when the script was run.
When you have more than one statement to be executed within a control structure, it's
necessary to surround them with brackets:
<?php
$x=1;
if ($x == 1) {
print '$x is equal to 1';
$x++;
print 'now $x is equal to 2';
}
?>
Keep in mind that the positioning of the elements does not affect the execution of the
script. All of the example arrangements below are perfectly valid not only for If
Statements, but for every form of control loop.
if ($x == 1) print '$x is equal to 1';
if ($x == 1)
print '$x is equal to 1';
if ($x == 1) { print '$x is equal to 1'; }
if ($x == 1) {
print '$x is equal to 1';
}
In the interests of clarity, many programmers opt to use indenting and brackets even on
one-line blocks of code; however, it is ultimately a matter of personal coding preference.
You can also include multiple conditions within parentheses. For the nested statements to
execute, all of the conditions must evaluate to true.
<?php
$x=1;
if ($x == 1 OR $x == 2) print '$x is equal to 1 (or maybe
2)';
?>
Else Statements
As the name implies, Else Statements allow you to do something else if the condition
within an If Statement evaluated to false:
<?php
$x=1;
if ($x == 2) {
print '$x is equal to 2';
} else {
print '$x is equal to 1';
}
?>
Else If Statements
Thus far, we have been able to respond to one condition, and do something if that
condition is not true. But what about evaluating multiple conditions? You could use a
series of If Statements to test each potential condition, but in some situations that is not a
suitable option. Here is where Else If Statements come in.
A combination of If and Else Statements, Else If Statements are evaluated sequentially if
the condition within the If Statement is false. When a condition within an Else If
Statement evaluates to true, the nested statements are parsed, the script stops executing
the entire If/Else if/Else Structure. The rest of the script proceeds to be parsed.
Take a look at the following example:
<?php
$x=1;
if ($x ==
print '$x
} else if
print '$x
2) {
is equal to 2';
($x == 1) {
is equal to 1';
} else {
print '$x does not equal 2 or 1';
}
?>
The final else statement can be left off if you do not want anything to happen if none of
the If or Else If Statements are true:
<?php
$x=0;
if ($x ==
print '$x
} else if
print '$x
}
?>
2) {
is equal to 2';
($x == 1) {
is equal to 1';
In this case, since neither the condition within the If or Else if Conditions are true, and no
Else Statement was provided, nothing would be outputted to the browser.
Switches
Switches are a good alternative to If/Else if/Else Statements in situations where you want
to check multiple values against a single variable or condition. This is the basic syntax:
<?php
$var = "yes";
switch ($var) {
case "yes":
print '$var is equal to yes';
break;
case "no":
print '$var is equal to no';
break;
}
?>
After running this code snippet, much of what is here will probably make sense to you. In
the first line of the switch statement, we have the identifier "switch" followed by a
variable surrounded by parenthesis. Each case includes a possible value for the variable.
Switches execute a little differently than If/Else if/Else statements. Once a case value
matches the value of the switch expression, every following statement is executed,
including those following other cases.
To prevent this from happening, a break statement is used. Break; ends the execution
of the switch statement, and lets the script continue execution; it can also be used in while
or for loops.
Optionally, you may also include a special case called "default". This case works much
like and Else Statement, and will execute if all the other cases are found to be false. This
case should be the very last one you include.
<?php
$var = "yes";
switch ($var) {
case "maybe":
print '$var is equal to yes';
break;
case "no":
print '$var is equal to no';
break;
default:
print 'none of the other two cases were true, so
this sentance will be printed out instead.';
}
?>
Similar to the Break Statement is the Exit Statement. Exit is particularly useful in
situations where you run into what would be considered a "fatal error" (for example, if
the user had entered a password that was incorrect) or any other time you needed to end
the execution of a script before it naturally terminated.
<?php
$var = "yes";
switch ($var) {
case "yes":
print '$var is equal to yes';
exit;
case "no":
print '$var is equal to no';
break;
}
print "this will not be printed, because the script will
have terminate before this line is reached";
?>
Unlike break, exit may be used anywhere in your scripts, inside or outside of control
structures.
The Ternary Operator
Though Technically an Operator, not a Control Structure, the Ternary Operator,
represented by "?", can be used as shorthand for simple If/Else Statements. It can only be
used in situations where you want execute a single expression based on whether a single
condition is true or false:
<?php
$x = 1;
($x==1) ? (print '$x is equal to 1') : (print '$x is not
equal to 1');
?>
The condition is contained within the first set of parentheses. If it evaluates to true, then
the expression within the second set of parentheses will be performed. Otherwise, the
expression in the third set will be performed:
(condition) ? (executes if the condition is true) :
(executes if the condition is false);
You will see how this can be particular useful a little later on.
Control Loops
Frequently in PHP there are instances where you need to perform repetitive tasks, such as
formatting data pulled from a database, sending out emails to a mailing list, or cycling
through the contents of an array. Control Loops allow you to perform these tasks almost
effortlessly.
While Loops
While Loops are the simplest form of loops:
<?php
$x=1;
while ($x <=10) {
print "$x<br>";
$x++;
}
?>
When you run this snippet, you will see the numbers 1 through 10 printed on your screen.
Take a look at the code. In many ways, it's very similar to an If Statement. First is the
while identifier, followed by a condition surrounded by parentheses.
The statements nested within the loop will execute as long as the condition within the
parentheses evaluates to true. Since the validity of the condition is checked before the
loop is executed, if the condition is false, then the statements within the loop will not be
executed at all.
Do...While Loops
Do...While Loops are close cousins of While Loops:
<?php
$x=11;
do {
print "$x<br>";
$x++;
} while ($x <=10);?>
The primary difference in how these work is that the validity of the condition in a
Do...While Loop is tested after the loop has itinerated once. This means that in the
example above, $x would be printed out one time, and then the execution of the loop
would end, because $x is greater than 10.
For Loops
<?php
for($x=1; $x<=10; $x++) {
print "$x<br>";
}
?>
The above is an example of a For Loop. For Loops are very similar to While Loops, but
more convenient to use in many cases. They are also the most complex loops in PHP,
borrowing syntax and function heavily from the C Programming language. This is the
final control struture we will be covering in this article.
If you guessed that the above snippet would output the same result as the first example of
a while loop, you would be right! Let's take a closer look at why it works like that.
Within the parentheses, For Loops take three expressions separated by semi-colons. The
first expression is only executed one time, when the loop initializes. In this case, $x is
created and given a value of zero.
The next expression is a condition that is checked each time the loop itinerates. Once the
condition is false, the loop will stop executing. Just like a while loop, if the condition is
found to be false on the first run, none of the statements within the loop will execute even
once.
The final expression will be executed each time the loop itinerates after the nested
statements have been parsed. Remember that there is no semi-colon after the final
expression.
As you can see, this for loop performs the same function as the earlier While Loop, but
far more concisely. Typically, it's best to use a For Loop in situations where you know
how many elements you will be cycling through.
The Foreach Loop
This new loop was introduced in PHP version 4. It s used exclusively for looping
through elements of an array, allowing you to easily print out or perform operations on
elements within an array. To keep things from getting too complicated, we will wait
cover this particular loop in detail when arrays are introduced.
Finally...
In this article we have covered the two types of Control Structures that PHP supports:
Conditional Statements and Control Loops. These Structures are at the core of controlling
program flow; the concepts introduced here will be used extensively from now on.
Next time, we will take take a look at pre-defined and user defined functions, which also
play an important roll in the logical development and execution of a script.
Stay Tuned!
Things to Remember:


Control Structures are at the core of programming flow,
allowing you to branch the execution of scripts based on input
and easily handle repeatitive tasks.
There are two types of Control Structures in PHP: Conditional
Statements and Control Loops.


Conditional Statements and Loops having only one nested
statement do not require brackets, however programmers
frequently use them to make code more understandable. Nested
statements are often indented for the same reason.
Break; can be used to end the execution of the current case. It
can also be used to break out of for loops and while loops. Exit;
terminates the execution entire script, and may be used
anywhere within the script.
Liz Fulghum currently lives in Annapolis, MD where she works as a web designer for a
custom shirt retailer. Liz was convinced to try PHP as an alternative to Perl; she has been
a fan ever since and frequently works as a freelance developer.
Other
A complete PHP application might contain upwards of dozens of individual script files,
with hundreds of lines of code in each. Between all of those, there will be many instances
where the same piece of code is reused: something as simple as outputting a string to the
browser or as complex as making sure a user is logged in across multiple pages, and
prompting them for login information if they are not.
As you might imagine, copying the same code you need to every location you need it in
is neither practical nor efficient.
Fortunately PHP, like most other programming languages, includes a language structure
called a Function. A Function is a self-contained code block that performs a specific job.
In most cases, they accept input from the main script as arguments, and return some kind
of result. They can help modularize a script by allowing the programmer to break the
script down by task. They are also portable, so if you write a useful function for one
script, you can easily reuse it in another.
In this article, we will be covering some introductory information on functions. We will
also be taking a brief look at PHP's pre-defined functions before focusing on creating and
using your own.
Pre-Defined Functions
One of things that makes PHP so easy to use is the wealth of built in functions. These
functions provide the tools to easily complete many of the everyday tasks you need to
perform in the course of writing a full-fledged application. There are functions for
working with just about everything in PHP: strings, arrays, databases, dates and times,
email, numbers, even functions for working with other functions.
With so many out there, it would be impossible to cover all of PHP's functions in a single
article. However, as the series progresses, you will be introduced to many of the more
useful ones. You can also find the complete list of PHP's built in functions at the their site.
Right now, let's take a look at a couple of these functions, just to explore how they can be
used.
print()
Though you have probably used it before without thinking about it, print(); is actually a
built in PHP function. Basically, print accepts a string as an argument and outputs it. It's a
little unique because it works with or without parentheses:
<?php
print "This is a test<br>\n";
print ("This is a test<br>\n");
?>
include()
include(), which allows you to include one file inside of another, is one of those functions
that you will find yourself using all the time. If you have ever seen web sites using php
where the links to other pages within the site look like
http://www.domain.com/?page=pagename or http://www.domain.com/?pagename, it is
likely that they are using this function to dynamically generate their web pages from
included files.
To see how it works, first create a file called test.txt and write some text in it. Next, create
a new PHP file called test.php and place the following inside of it. Just like print(), the
parentheses are optional:
<?php
include "text.txt";
?>
Make sure both are saved to the same directory on your web server. When you run
test.php, you will see that the text you placed in text.txt was outputted to the browser.
You can easily include text, html or php files in this manner.
header()
This function allows you to send a raw HTTP header. Most of its applications are
technical, but one of the most common uses is something relatively simple: redirecting
the user. This has the same effect as the META redirection tag in HTML:
<?php
header( "Location:http://webdeveloper.earthweb.com/");
exit;
?>
Keep in mind that if you use header(), it must be called before outputting any information
to the browser, either from PHP or HTML.
Arrays in PHP
Arrays fall under the same category that a lot of concepts in PHP do: "Difficult to
understand at first, easy to use once you do, and impossible to live without."
In this article, we will be taking a look at why they are so important to program
development, and explore how to work with them. You will also learn how you can write
a random link generator using arrays, and expand it to display banners or buttons
associated with the links.
So, What Exactly are Arrays?
Arrays, common to almost every programming language in one form or another, are a
data type which allows groups of related data to be stored in a structured table-like format.
Simple arrays look a lot like a database or spreadsheet from your favorite office suite, and
can be manipulated in much the same way.
In PHP, an array is assigned to a single variable, but it can hold dozens of individual
pieces of information. Each individual bit of information, or row, is referred to as an
array element. Within every array element there are two parts: the value, which contains
the actual information you want to store, and a unique key which identifies the value.
You'll learn later how keys play an important role in the process of accessing and
manipulate array elements.
Keys can either be non-negative integers, or strings. Arrays with integers as keys are the
most common types and known as Scalar Arrays. Those with strings as keys are called
Associative Arrays.
If you were to visualize an Array, it would look something like the example in Figure 1.
This array is called $Array. It has 5 values, and is considered a scalar array because the
keys are integers.
It would also be classified as a One-Dimensional Array, because it holds only a single
layer of information. PHP includes supports Multi-Dimensional Arrays as well, which
allow you to have multiple layers of information. We will touch on Multi-Dimensional
Arrays a later on in the article, but for now, let's keep it simple.
Creating and Populating Arrays
Arrays are created using the array function:
<?php
$Array = array();
print $Array;
?>
When this script is run, you will see that the only output is "Array". Since an array is
merely a container for data, any time you try to print out a variable with an array assigned
to it without referencing a particular element, PHP outputs "Array".
So far, our array does not anything in it, so let's take a look at some of the different ways
you can add data to it.
The first way to add elements is by passing them to the array function:
<?php
$Array=array("http://www.yahoo.com",
"http://www.internet.com", "http://www.google.com",
"http://www.cnn.com/","http://www.php.net/");
?>
Notice that we did not assign any keys for the values. You have the option of leaving the
keys out -- in which case PHP will automatically assign numerical ones -- or explicitly
setting them.
It s important to remember that when you allow PHP to set the keys, the first element
will always be assigned an index of 0, not 1. If you already have some keys specified,
PHP will assign the next highest integer to act as the key for the values not assigned:
<?php
$Array=array(1 => "http://www.yahoo.com", 2 =>
"http://www.internet.com", 3 => "http://www.google.com",
"http://www.cnn.com/", "http://www.php.net/");
?>
You can also assign string values as keys in much the same manner:
<?php
$Array=array("yahoo" => "http://www.yahoo.com",
"internet" => "http://www.internet.com", "google" =>
"http://www.google.com", "cnn" => "http://www.cnn.com/",
"php" => "http://www.php.net/");
?>
The second way to assign values is to explicitly set them. In addition to being used to
initially populate an array, this method can also be used at any time to add new elements
to an existing array, or alter an existing element by setting a new value. Including the new
array statement is optional, as PHP will automatically create the new array if it doesn t
exist when you try to add elements:
<?php
$Array = array();
$Array[]="http://www.yahoo.com/";
$Array[]="http://www.internet.com";
$Array[]="http://www.google.com";
$Array[]="http://www.cnn.com/";
$Array[]="http://www.php.net/";
?>
Again, these values have been added without explicitly declaring a key for them, but you
can easily assign numerical or associative keys:
$Array[1]="http://www.yahoo.com";
or
$Array["yahoo"]="http://www.yahoo.com";
Which method you use on a daily basis is largely up to personal preference; however, the
second method has the benefit of being slightly more readable when working with long
pieces of data.
Outputting Elements from Arrays
So, now that we have data in the array, how do we access it? This is where keys begin to
play an important role.
Looking at Figure 1, and remembering that PHP automatically assigned key to this array
(beginning with 0), it's easy to access a specific array value using its index. Try the
following script:
<?php
$Array=array("http://www.yahoo.com",
"http://www.internet.com", "http://www.google.com",
"http://www.cnn.com/", "http://www.php.net/");
print $Array[0];
?>
Since we are accessing the array stored in the variable called $Array, and the element
assigned to the key with a value of "0" is specified, this script outputs
"http://www.yahoo.com".
If you wanted to print out every element in the array, you could do it by specifically
referencing the key for each one like this:
print "$Array[0] $Array[1] $Array[2] $Array[3]
$Array[4]";
But as you can see, it would quickly get cumbersome if you had a more than a few
elements.
To make things easier, PHP also allows you to iterate through arrays using loops. The
foreach loop is specifically designed to work with arrays:
<?php
$Array = array();
$Array[]="http://www.yahoo.com/";
$Array[]="http://www.internet.com";
$Array[]="http://www.google.com";
$Array[]="http://www.cnn.com/";
$Array[]="http://www.php.net/";
foreach($Array as $key => $value) {
print "$key: $value<br>";
}
?>
The loop advances an internal pointer through each row of the array, assigns the key and
the value to variables, and then prints out one or both of them until the end of the array is
reached.
In this example, every key and value in the array would be outputted to the browser, but
if you did not need to use the key of the array for anything, you could simplify the loop
even further:
foreach($Array as $value) {
print "$value<br>";
}
Within the foreach loop, you can easily perform operations on the array elements and
include other control structures to drilldown to the information you want:
foreach($Array as $value) {
if($value == "http://www.yahoo.com") {
print strtoupper($value);
}
}
In the above example, nothing would be printed out until the value of an element within
the array was equivalent to "http://www.yahoo.com". At that point, the $value would be
capitalized using strtoupper() and printed out.
A foreach is not the only way to move through an array. If you have a scalar array
indexed automatically or manually, without gaps, you could also use a for or while loop
to move through the array:
for($i=0;$i<=count($Array);$i++) {
print "$Array[i]<br>";
}
or
$i = 0;
while ($i <= count($Array)) {
print "$Array[i]<br>";
$i++;
}
These two snippets essential do the same thing: beginning with a count of 0, print out the
array element with the key equal to the value of $i, increase the value of $i, and repeat.
This continues until $i is equal to the number of elements within the array, which is
found by using count($Array);
As you can see, these two methods are a little more verbose than using a foreach loop,
but they are both perfectly acceptable methods in most situations.
PHP in FORMS
Once you know the basics of PHP s syntax and structure, it is fairly easy to make the
leap to writing full-fledged scripts.
Because working with forms is one the most common tasks in writing applications for the
web, the first script we write will be a form processor. Though a fairly mundane
application, it will introduce you to a range of important concepts, including how PHP
handles variables that come from outside the running script.
First, let s take a quick look at the HTML end of forms, and go into a little bit of detail
about how data is passed from forms to the server.
Form Basics
You have probably worked with HTML forms dozens of times, but have you ever really
thought about how they work?
Take a look at the following:
<html>
<body>
<form action="page.php" method="post">
<input type="text" name="name" value="">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
This is probably one of the simplest forms you could have in a page. It contains a text
field called "name" and a submit button. Notice the method specified in the opening form
tag.
As you might remember, there are two options for the method -- GET and POST -- which
determine how information is passed from the form.
Without getting technical, here's the difference: GET sends the form information
appended to the URL which is the same way that information is sent from a link. POST,
on the other hand, sends the information transparently as part of the header of the page
request.
Unlike GET, information sent via POST is not affected by any browser limitations on the
length of URLs, and is not visible to the user. It is for this reason that POST is usually the
chosen method for forms, unless you are debugging your script and need to see what is
being passed to it. You will see why this distinction is also important to remember for the
purposes of programming a little later on.
From the Form to PHP
Once a server receives information from a form posted to a PHP script, the programming
takes over. This is where PHP really starts to shine. Every value passed from the form is
automatically available to the script using the name given to the input in the form. For
example, if you used the sample form above, and entered "Billy Joe Bob" for the name,
then the name of that value in the script would be accessed as a variation of "name".
The version of PHP running and configuration of the php.ini file determines exactly what
variation the value will be available by. These settings affect forms and data passed via
links as well as predefined server and environment variables. Here are the possible
situations:
1. track_vars setting is on in the php.ini file: GET, and POST variables (among
others) will be available through global arrays: $HTTP_POST_VARS and
$HTTP_GET_VARS. For example: $HTTP_POST_VARS["name"]. Note: these
arrays are not global.
2. register_globals setting is on in the php.ini: GET and POST variables will be
available in the format of standard variables. For example: $name. Variables
passed from forms are automatically part of the global namespace.
3. register_globals and track_vars are on in the php.ini: variables are available in
both forms.
4. PHP version 4.1.0 and higher: Due to security concerns, register_globals is being
deprecated. Though still on in default configurations of 4.1.0, following releases
will not have the setting enabled. New, shorter, arrays have been introduced to
replace the old $HTTP_POST_* arrays: $_GET, $_POST. These arrays are also
automatically global. For Example: $_POST['name']
For the remainder of this article, as well as this series, the newest $_* arrays will be used
when handling variables from outside of PHP. If you are using an older version of PHP,
you will need to replace the variables used in the sample scripts with the format that
works under your particular configuration; however, it s also advisable to upgrade to the
newest version of PHP as soon as possible.
Writing a Form Mailer
Before you write any script, it is important to analyze what functions you need to perform
and come up with a brief outline. For this script, there are a couple of things we want to
include beyond simply sending the contents of the form: - Display a form and allow the
user to submit their name, email and a message. - Make sure all required fields are filled
in. - Display a message and redisplay the form if required fields are missing. - Do some
simple validation on the user s email address. - Send the user's message via email Display a thank you page. Just like any other project, having a mental or written
blueprint of what you want to do cuts down on the amount of changes because you forgot
something and makes writing the script easier and faster.
The Form
<html>
<body>
<br><br>
<?=$errormessage?>
<br>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<table width="500" border="0" cellpadding="5" cellspacing="0">
<tr><td>Your name:</td><td><input type="text" name="name"
value="<?=$_POST['name']?>"></td></tr>
<tr><td>Your email:</td><td><input type="text" name="email"
value="<?=$_POST['email']?>"><td><tr>
<tr><td>Your message:</td><td><textarea
name="message"><?=$_POST['message']?></textarea></td></tr></table>
<input type="hidden" name="required" value="name,email,message">
<input type="submit" name="submit" value="submit">
</body></html>
Save this as form.php and take a look at it. For the most part, this form is strictly HTML.
There are 3 input fields: name, email and message that the user will fill out.
Since the scripting that handles the form input will be in the same file as the form itself,
we use $_SERVER['PHP_SELF'], a server variable representing the file name of the
script that is currently running, as the form action. Essentially, we are posting the form
back to the current URL, whatever that may be.
<?=$errormessage?> does not output anything unless there is an error in the user input in which case its replaced by the error message.
Also notice that PHP is used to set a default value for each of these fields. If the user
leaves one of the required fields blank, we will want to redisplay the form. To keep them
from needing to re-type information, we use the values from the first time they submitted
the form to pre-fill the fields.
The hidden field contains a comma delimited list of the field names we want to be
required; it will be used to cycle through all of the values to check to see if they are filled
in once the form is submitted.
The PHP
As mentioned before, the PHP to process the form will be in the same file as the HTML.
This makes it easy to redisplay the form should there be an error in what the user
submitted. So that the PHP is parsed immediately after the form is submitted, it should
appear in the file before the HTML. If the form is validated, we will send the email and
stop the execution of the script before the form is reached again. If there is a problem
with what the user submitted, we will assign an error message to $errormessage and the
form will automatically be displayed, since it comes after the PHP.
The first line of PHP needs to check to see whether or not the form has been submitted.
The easiest way to do this is to see whether a value from the form is present or not. Since
the value of the submit button is always passed with the form, it is idea to use for
checking:
<?php
if ($_POST['submit']) {
print "the form has been submitted";
}
?>
Add this code snippet before the html for the form in form.php, and run the file from your
browser. When you fill out the form and press submit, you will see "the form has been
submitted" at the top of your browser, followed by the form. Putting all the code to
validate and send the contents of the form within this if statement will ensure it will only
execute if the form has been submitted.
The next step is to check and make sure that all of the required fields are filled out. To do
this, we need to grab the list of required fields from the hidden form field and split them
into an array. Once they are in array form, we can loop through them checking to make
sure the associated variables are not empty.
To split the list, we can use one of PHP s built in functions, explode(), which "explodes"
a string on the occurrence of another string, and assigns the results to an array:
<?php
if ($_POST['submit']) {
$required_fields = explode(",", $_POST['required']);
Now that we have an array that contains the required fields, we can loop through it. If a
field does not have a value, we need to indicate that it's missing. The easiest way to do
that is by incrementing a counter each time a variable is empty:
$error = 0;
foreach($required_fields as $fieldname) {
if ($_POST[$fieldname] == "") {
$error++;
}
}
Here the execution of the script branches.
If $error is still equal to 0 after the end of the loop then we know that the user filled in all
the fields and we can go on to do some simple validation of the email address:
if ($error == 0) {
if (strstr($_POST['email'], "@") and strstr($_POST['email'], ".")) {
Using the built in PHP function, strstr(), this if statement simply checks to make sure
there is a @ and period in the email address. Though you can perform more complex
validation that checks for the proper syntax of email addresses, and even checks to make
sure the entered domain name is valid, this will weed out the more creative fake
addresses a user might enter.
If the email address contains both of these values, then we can send the user s email.
PHP includes a function to send email called mail(). It follows the following format: mail
(TO, SUBJECT, MESSAGE (optionally:, additional headers, paremeters).
Optional additional headers includes information such as the From and Reply To
addresses, any additional recipients and the content type (for sending email as plain text
or html) to name a few. For this script, though, all we need are the basic parameters
(remember to replace "youremail@your.com with your own email address):
mail("youremail@your.com" , "Message from Web
Form", $_POST['message'], "From: $_POST[name]
<$_POST[email]>");
After sending the email, we need to display a message to the user letting them know that
their email has been sent. Since they submitted their name, we can use it to personalize
the message:
print "<html><body>Thank you for submitting your
comments $_POST[name]!</body></html>";
exit;
Or even better, redirect them to another page:
header("Location:http://yourdomain.com/thanks.php?name=$_POST[name]");
exit;
Since we passed the name appended to the URL in the second sample, you could also use
it in thanks.php in the form of $_GET['name'] (remember, variables passed via urls are
available in the $_GET array). Including the exit statement after the print or header
statement ends the execution of the script; it is used here so the form is not redisplayed.
Now that we have handled the part of the script that sends the email, we need to work
more on the error handling. We bundled the code block for validating the email within an
if statement checking to make sure all the fields, and the code block for sending the email
within the if statement validating the email. To display a message if there are errors in the
form, we need to work backwards logically.
First, the if statement for the email validation is closed, and an else statement is defined
to display a message should the email not validate:
} else {
$errormessage = "<b>The email address you
entered does not appear to be valid<br></b>";
}
Finally, the if statement for the field checking is closed and an else statement is added to
specific what should happen if any fields are empty, the opening loop to see if the form
was submitted is also closed:
} else {
$errormessage = "<b>You have left some required
fields in the form blank! Please fill in the form
completely.";
}
}
?>
That s all there is to it. You can view the whole script here, or save your working file
and test the form in your browser.
Finally
You can easily expand on this form for all different sorts of applications. Next time, we
will explore how to work with files, and revisit forms to create scripts that store and
update information on the server. Stay Tuned!
Things to Remember:



Forms can either be sent using the GET or POST methods.
GET works the same way links work: data is sent by being
appended to the URL. POST sends form data as part of the
header request. This method is more secure since the user
cannot see the information that's being passed and is not
affected by any limitations browsers may have on the length of
the URL
Name/value pairs passed to a PHP script via forms (or links)
are automatically available.
Depending on the version of PHP and the configuration of the
PHP.ini, the extact format of external variables (including those
sent via forms and links as well as server and environmental
variables) may differ.
Liz Fulghum currently lives in Annapolis, MD where she works as a web designer for a
custom shirt retailer. Liz was convinced to try PHP as an alternative to Perl; she has been
a fan ever since and frequently works as a freelance developer.
Whole Script:
Download