php

 

repompe de http://idm.internet.com/articles/200005/phpindex.html

 

Welcome to PHP


An Intranet Design Magazine Tutorial

By Aaron Weiss

 

Introduction

Early era web developers with dynamic ambitions had little more than server side includes in their toolbelts -- it was a dark era indeed. The need for embedded server-parsed scripting languages was apparent, and Microsoft went after this hunger with their ASP, or Active Server Pages, technology. The concept behind ASP, and all other embedded server-parsed languages, is premised upon embedding programming code within the HTML that makes up a web page. The web server interprets and executes this code, replacing the code with its results, and delivering the resulting web page to the browser. Popular though ASP became, many developers continued wanting for a more stable and less proprietary solution: enter PHP, an open-source server-parsed embedded scripting language.

In this introduction we'll take a look at programming with PHP 3, the most popular version of PHP, although PHP 4 is just around the corner. The art and science of computer programming is a much larger topic than any one language, and cannot be the focus of this introduction -- while PHP is accessible to programming newcomers, it will be easiest for those with even a small background in programming other languages such as BASIC, Pascal, C, JavaScript, Perl, and so on.

Why PHP?

Developers have literally flocked to PHP, with its modest learning curve, free and open development, native database connectivity, stability, and availability for a variety of platforms. Still, it is important to understand that PHP is not a unique solution to web development -- we're fortunate these days to enjoy a potpourri of possible web development tools with which to work. Many tasks can be performed with a wide variety of technologies, so one has to weigh many factors in choosing a development path: past experience, platforms, time-to-market, and so forth. Many Perl developers, especially, wonder about the value of PHP. In truth, PHP like any language offers several advantages and also possesses several disadvantages to consider.

PHP's primary strength is in rapid development of dynamic web pages. Developers without heavy programming experience can leverage PHP to complete tasks otherwise cryptic or obtuse in altnerative languages, such as pulling records from a database and inserting them into an HTML table. The architecture of the PHP language is simple but powerful, and includes an extremely wide variety of functions suited for many tasks, both traditional data processing tasks and more web-oriented functions as well.

On the other hand, one could argue that PHP remains an immature language, without the architectural elegance or extensibility of Perl, for instance. Whereas some developers find embedded scripting, where program code is often mixed together with HTML structure, empowering, other developers find this approach disorganized and bug-prone, preferring separate development environments for each web component. Developers with experience in Perl and especially mod_perl environments may find little reason to spend time with PHP, and this may be entirely justifiable.

That said, this is an introduction to PHP, so let us assume you are at least a bit curious!

The Very Basics

We shouldn't ignore the simple fact that PHP pages require a web server with PHP support. At this time of writing, there are only two real methods of using PHP with a web server: either executing the PHP interpreter from a CGI wrapper, so that PHP runs as any CGI script would, or integrating PHP with the Apache web server. While the CGI wrapper method should work with a wide variety of web servers, it is the least efficient in exeuction speed and resource consumption. Apache+PHP is the preferred solution, although in the future we should also see PHP integrated into other major web servers.

Unfortunately, installing and configuring your web server to properly execute PHP pages is not really the focus of this article, and can be a complex subject due to the variety of operating systems and web servers that might be involved. This article will here on in assume that your web server is already setup to serve PHP pages. If that's not the case, you'll want to begin at the PHP web site (http://www.php.net) to learn how to download and install PHP for your web server. If you don't run a web server, but rather use the services of a web host such as your Internet Service Provider, they will need to support PHP for you.

PHP is not a client-side language. That means that browser never sees PHP -- only the web server sees it, and executes it on-the-fly. The browser receives only a "normal" HTML page. To achieve this, PHP code is contained within a special tag, separating it from the other HTML on the page:

<H2>Today's Headline:</H2><BR>
<P ALIGN="center">
<?php
 your php code here
?>
</P><HR>

Consider a very simple sample, where the PHP code simply outputs the phrase "World Peace Declared":

what the web server sees what the web browser receives
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php
 print "World Peace Declared";
?>
</P><HR>
<H2>Today's Headline:</H2>
<P ALIGN="center">
World Peace Declared
</P><HR>

And of course, the web browser will render on-screen:

Today's Headline:

World Peace Declared

 

PHP Structure

All of the PHP code within one web page is considered to be one PHP "script". You are free to break up the code into multiple <?php ... ?> sections, as needed. For example, we might set a variable containing today's date at the beginning of a page, which is then used for output later in the page. Let's call our ongoing example script worldpeace.php3. Note that PHP pages usually have the filename extension .php3, as that is the default filename that the web server will look for. This can be changed by reconfiguring the web server.

worldpeace.php3:

<?php
 $today=getdate(time());
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
 <?php
  print "World Peace Declared";
 ?>
</P><HR>
<!-- begin footer -->
 <SMALL>Today is <?php
  print $today[weekday];
  ?></SMALL>

We haven't yet discussed the PHP language itself, so let's focus on structure for now. The above page contains a small section of PHP code, which assigns a value to a variable $today. A second block of PHP code in the middle of the page outputs our headline, and a third block of PHP near the end of the page uses the $today variable to output the day of the week. Given that today (the day I'm writing this, not necessarily the day you're reading it!) is Wednesday, the above code would produce the page:

Today's Headline:

World Peace Declared


Today is Wednesday

Besides breaking up PHP code into multiple blocks, it is also possible to include code from external files into your pages. Sometimes you wish to keep bits of code in its own file -- for instance, HTML code that makes up a repeating element such as a logo or footer, or PHP code that makes up a function that you might want to use in several different pages. Returning to the previous example, suppose we break out the footer into its own file, and the initial PHP block into its own file:

setdate.php3:
<?php 
 $today=getdate(time());
?>
footer.php3:
<!-- begin footer -->
<SMALL>Today is <?php 
 print $today[weekday];
?></SMALL>

Now, we can use PHP's include() function to pull the above files into our example page:

<?php
 include ("setdate.php3");
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
 <?php
  print "World Peace Declared";
 ?>
</P><HR>
<?php
 include ("footer.php3");
?>

The most common use for the include() function is, as seen above, to reuse certain components across several pages. Of course, your components will often contain much more code that the examples seen here! Also notice that each component is treated as an HTML page -- that is, it can contain HTML tags and any PHP code must appear within the <?php ... ?> tags.

Scalar Variables and Data

 

We've seen how a PHP page looks, and how the code can be structured -- but that's all. Only one thing missing ... the language itself! And so begins the rest of our journey. The PHP language shares much in common with other popular programming languages, especially Perl and C. If you have any experience with these, PHP will be a snap. Non-programmers will find PHP straightforward, but must understand that the art of programming is a separate matter from the syntax of a particular language -- just as cooking a gourmet meal requires more than just a list of ingredients, and writing a work of literature requires more than a knowledge of spelling and grammar.

In most cases, your PHP scripts will work with data -- to process, manipulate, and output. Data generally consists of numbers (numeric values) and letters or words (string values), although there are other types of data that PHP understands.

  • Integers and floating-point numbers are the two numeric data types in PHP.

    An integer is any whole number such as 5, 10, 0, or -3.
    A floating-point number is any number with a decimal portion, such as 5.25 or -43.2339 and so on.

  • String data is composed of any alphanumeric characters, such as words or symbols. Examples of strings include "pepsi", "The Simpsons", "23 skidoo", "Yahoo!", and so on.

Integer, floating-point, and string values are all known as scalar data because they are single data points. This is another way of saying that the number 5, or the word "hockey", is just "one thing" (as opposed to, say, a list of things which we will see shortly).

In PHP as with most programming languages, we use variables to contain a value -- a variable is like a label that refers to a value. The value assigned to a variable can change over time, as a result of processing and manipulation such as arithmetic. Variable names are usually words and are preceded with a dollar sign ($) in PHP. Let's assign the value 100 to a variable named $price:

$price = 100;

Code snippets such as the above are examples, but remember that PHP code in a page must always appear within <?php ... ?> tags, even though we won't always write those tags around every single example snippet.

Also notice that good practice suggests we end PHP statements with a semicolon, as seen above. A statement is sort of like an English sentence -- it is one full programming "thought". PHP statements are made up of expressions, where an expression is a meaningful fragment of code. The previous example represents an assignment expression, because a value has been assigned to a variable. In this case, the statement happens to be made of only the one expression, which is perfectly fine. Many PHP statements are made up of several expressions, which we'll see later.

PHP determines the data type of a variable based on context, such as the context of the assignment expression:

$price = 100;
$firstName = "Martin";
$breed = 'ferret';
$name = $firstName;

In the first line above, which we've already seen, PHP assumes that 100 is an integer. In the second line, PHP understands Martin as a string because it is enclosed in double quotation marks. The same applies to ferret, although enclosed in single quotation marks. In the fourth example, $name is assigned whatever value is currently held by $firstName, which happens to be a string, so $name also contains a string value (Martin).

Note that in the fourth example, $name receives a copy of the value in $firstName. Thus, if we then change the value of $name, this has no effect on the value held by $firstName.

Important: Variable names in PHP are case-sensitive. In other words, the variable $firstName is completely independent from a variable named $firstname.

Why does a value's data type matter to PHP, or to us for that matter? It matters when you need to perform an operation on one or more values. Operations include arithmetic such as addition and subtraction. For instance, you can add an integer and a floating-point value to yield another floating-point value:

$total = $price + 3.95; #flat rate shipping

Above, $total will contain the value of whatever $price contained plus 3.95. Also notice the use of a comment marked by a pound sign (#) -- PHP will ignore everything from the pound sign to the end of that line, so that we can add annotations to clarify the purpose of a line of code.

But suppose you tried to add an integer and a string value?

$total = $price + "fruit juice";

Of course that doesn't make any sense! PHP will try to resolve this problem by converting a string to a number, if the string looks like a number such as "4.50" (converts to 4.50) or even "10 apples" (converts to 10). In the above example, PHP can't make any number out of "fruit juice", so it will be given the value 0, and 0 is what will be added to $price.

Variables are a crucial component of most programming languages including PHP -- you will use them to store pieces of data, manipulate the data, and usually output some of the data.

Data collection: Arrays

Earlier we said that scalar values were just "one thing", or a single data point. Sometimes you need to contain a series or collection of "things". For example, suppose you want to keep a list of colors. A list, if you think about it, is really a collection of scalar values: "blue", "indigo", "yellow", and so on. Programmers call such a list an array, and PHP provides support for arrays.

Experienced programmers will note that in PHP, an array is both a list or indexed array and an associative array or hash table -- there aren't two different types of arrays. In this sense, all PHP arrays are really associative arrays but can be treated as indexed arrays where the indices are keys. If the previous sentence made no sense to you, don't worry about it, this is mostly important to those familiar with other languages' types of arrays.

Assigning a collection of values to an array variable is simple using the array() construct:

$colors = array("blue","indigo","yellow");

Or, if you know that you want to create an array $colors but don't yet know what values to fill it with, create an empty array:

$colors = array();

Adding new values to the array is a breeze:

$colors[] = "hunter green";

Now the array $colors contains four values. Often times, you need to access a single item in an array, such as for output or a calculation. To do this, you need to refer to a key, which leads to the value you want. We haven't created any keys ourselves in this example, and so PHP has created numeric keys: the key for the first item ("blue") is zero, the key for the second item is one, and so on, with the key for the last item in a list being the number of items minus 1, since keys begin at zero. So, we can output the second color in the array via the key 1:

print $colors[1];

...will output "indigo". This type of indexed key system is great when you want to keep items in a specific order, but it's also limiting because the keys don't really mean anything. How do we know we want the second key? In some applications we do know ... in others, this thinking just doesn't work. The alternative is to create keys which are meaningful labels. For instance, suppose our collection of colors was really a list of colors for our car. A car may have several colors, depending on the part of the car -- exterior, trim, fabric, dashboard. Here it makes sense to use keys which are labels more meaningful than a mere index:

$colors = array("exterior"=>"blue",
                "trim"=>"indigo",
                "fabric"=>"yellow",
                "dashboard"=>"hunter green");

Admittedly, this is one ugly car. Our list items have gained meaning but lost order -- which is fine, since this list is not about order. It's now easy to output the fabric color of this car, because "fabric" is a key in the list:

print $colors[fabric];

...will output "yellow".

Once you've built an array, you typically need to manipulate it somehow, such as to sort it or simply output each of its values. PHP contains a variety of functions for working with an array, most of which we won't cover here. Let's say, though, that we wanted to output each of the items in $colors, along with the key associated with that item. The general procedure for "stepping through" an array and processing each of its items will apply to many arrays you use in the future -- let's use this procedure on $colors.

while (list($key,$value) = each($colors)) {
	print "$key: $value<BR>";
}

Although we haven't yet discussed the while loop yet, bear with us! The above code sets up a loop, or a series of repeating steps. The each() function returns a list (array) of values corresponding to the key and value for a single item in the array. These returned values are assigned on-the-fly to $key and $value, courtesy of the list() function. The print statement simply outputs the key and value for the current item in the list -- of course, you could do much more complex things with these values at this point in the code. Each time the loop returns to the while statement, it gets the next item in the array. When the array is completed the while loop will end.

In the browser, the above code would output:

exterior: blue
trim: indigo
fabric: yellow
dashboard: hunter green

Notice the order of our output, though -- same order that these items were defined earlier in our original array() statement. Suppose instead that we'd like to sort this array alphabetically by key, so that "dashboard" appears first and "trim" last. Simply, use PHP's ksort() function to sort $colors by key, and then step through the array as before:

ksort ($colors);
while (list($key,$value) = each($colors)) {
	print "$key: $value<BR>";
} 

The PHP reference manual details a variety of additional functions for managing your data arrays and performing nifty acrobatics.

PHP Variables and Web Forms

One of the more popular uses of server-side scripts is to process form submissions from web pages. PHP makes it especially easy to bring the values from form fields into your PHP code. Let's take a simple HTML form, a single-line text field where a visitor can enter their e-mail address, as coded in HTML:

<FORM action="process.php3" method="get">
 Please enter your e-mail address: 
 <INPUT type="text" size=20 name="email">
 <BR><INPUT type="submit">
</FORM>

When the above form is submitted, a parameter named "email" with whatever value the user entered will be submitted to the PHP script process.php3. Within that script, a variable named $email will automatically be created with the value from the form:

process.php3:

<?php
 print "Your address, $email, has been added to our mailing list.";
 addToMaillist($email);
?>

Note that addToMaillist is a fictional function, that we might have created to place the user's email address into a text file somewhere.

Because PHP migrates form field names into variables, you may wish to construct form field names with an eye towards their resulting data structure in PHP. For instance, suppose you have one form that asks for information about a recipient of some sort. You may want to contain that form's values inside a $recipient array, for example, to improve data management inside your PHP script:

<FORM action="process.php3" method="get">
 Please enter the recipient's e-mail address: 
 <INPUT type="text" size=20 name="recipient[email]"><BR>
 Please enter the recipient's full name: 
 <INPUT type="text" size=20 name="recipient[name]"><BR>
 <BR><INPUT type="submit">
</FORM>

process.php3:

<?php
 while (list($key,$value) = each($recipient)) {
 	print "$key: $value<BR>";
 }
?>

The HTML form above was migrated into a PHP array named $recipient with the keys email and name. Above, our PHP code simply reproduces the loop we saw earlier and outputs each key and value in this array, for instance (depending on what we submitted in the form):

email: cat@doglover.net
name: Mrs. Kitty


Operations and Comparisons

 

We've seen that PHP scalar variables contain values, whether numeric or string. In the course of your program, you'll often want to operate on these values -- an operation can include an arithmetic calculation, for example, or a comparison between values to find which is smaller, larger, or so on. PHP provides a basic set of operators good for most common data manipulations.

In fact, we've already worked with one operator -- the assignment operator -- also known as the equal sign used to assign a value to a variable, such as:

$val1 = 5;

Arithmetic operators, as the name implies, let you perform math on one or more values. Computers love doing math, so PHP always get a kick out of performing arithmetic operations. The table of expressions below summarizes PHP's arithmetic operators and how they work. For all examples, assume that $val1 contains 5 and $val2 contains 12.

PHP Arithmetic Operators
Operator Name Description Example Yield
+
Addition Sum of two expressions.
$val1 + $val2
17
-
Subtraction Difference between two expressions.
$val1 - $val2
-7
*
Multiplication Product of two expressions.
$val1 * $val2
60
/
Division Dividend of two expressions.
$val2 / $val1
2.4
%
Modulus Remainder left over after the division of two expressions.
$val2 % $val1
2
++
Unary increment Increases value of a single variable by 1.
$val1++
6
--
Unary decrement Decreases value of a single variable by 1.
$val1--
4

Note in the table above that we often refer to the term "expressions", as in "sum of two expressions". It would be too limiting to say "sum of two variables", because we could write code such as:

$val3=(5-$val1)+$val2;

This statement actually consists of three expressions: the assignment operation, between $val3 and everything to the right of the equal sign; the addition operation between $val2 and the expression to the left of the plus sign; and finally, the subtraction operation within parentheses. Why the parentheses? This raises the issue of operator precedence. When an expression contains several operators, PHP has to determine in what order to perform the operations. Sometimes this matters greatly. Consider:

$val1 = 2 * 4 - 3;

What value should be assigned to $val1? If we first multiply 2 and 4, and then subtract 3, the result would be 5. But if we first subtract 3 from 4, and then multiply that by 2, the result woudl be 2. PHP has a set of precedence rules which define which operations take precedence -- in this case, multiplication is of higher precedence than subtraction, so in this case PHP would come up with the first interpretation, resulting in a value of 5.

To be honest, the operator precedence rules can be quite difficult to remember. Rather than memorizing them all, a better approach is often to use parentheses to group operations -- this way, we can determine our own precedence. For example, we can use parentheses to determine either of the previous two interpretations:

$val1 = (2 * 4) - 3;
$val1 = 2 * (4 - 3);

The first example will yield 5, while the second will yield 2. You're usually better off using parenthetical grouping this way rather than relying on PHP's implicit precedence rules, both because they can be difficult to remember, and because the above code will be easier to understand by a human at a later time.

 

String operators work with characters rather than numbers. And of course you can't really add, subtract, or multiply the words "hot" and "tamale". Then again, maybe you can "add" them, if by that you mean string them together. In fact, this is called concatenation, and it is the only string operator available in PHP. Rather than a plus sign, the PHP concatenation operator is a single dot, or period. Imagine that $firstName contains "Woodrow".

$fullName = $firstName . "Wilson";

Now, $fullName will contains "WoodrowWilson". Whoops -- we'd probably want a space between those words, something to keep in mind when you concatenate strings:

$fullName = $firstName . " Wilson";

Simple, indeed.

 

PHP's basic assignment operator is already familiar, being a simple equal sign (=). You can also combine the equal sign with an arithmetic or string operator to make a "shortcut" assignment. Confused? Let's illustrate -- suppose that you'd like to add a value of 5 to whatever value is currently contained in $val1:

$val1 += 5;

Thus, if $val1 was previously valued at 10, after the above statement it would contain 15. Similarly, you can use the same shortcut for string concatentation, if you want to add a string to the end of an existing string. Suppose $name contains "Thelonius":

$name .= " Monk";

And now $name will be "Thelonius Monk".

 

Comparing two values is frequently useful -- is a purchase total below a certain threshold, or is does one word come before another alphabetically? PHP's team of comparison operators is here to help! A comparison operator ultimately returns either a true or a false value, depending on the result of the comparison. What you do with this result value can vary, and we'll see this more closely when we talk about control statements. For the examples below, let's assume the following variable values:

$val1 = 15;
$val2 = 7;
$name1 = "Martin";
$name2 = "Michael";

PHP Comparison Operators

Operator Name Description Examples Yields
==
Equality Tests whether two expressions are of equal value. For strings, the two must be exactly the same.
$val1 == $val2
$name1 == $name2
false
false
!=
Inequality Tests whether two expressions are not equal, or for strings, not exactly the same.
$val1 != $val2
$name1 != $name2
true
true
<
Less than Tests whether the lefthand expression has a value smaller than the righthand expression. For strings, smaller means "comes before alphabetically".
$val1 < $val2
$name1 < $name2
false
true
>
Greater than Tests whether the lefthand expression has a value greater than the righthand expression. For strings, greater means "comes after alphabetically".
$val1 > $val2
$name1 > $name2
true
false
<=
Less than or equal to Tests whether the lefthand expression is of equal or lesser value than the righthand expression.
$val1 <= 15
$name1 <= "Martin"
true
true
>=
Greater than or equal to Tests whether the lefthand expression is of equal or greater value than the righthand expression.
$val2 >=6
$name2 >= "Manfred"
true
true

 

Let's raise the stakes: comparing two values is one thing, but sometimes you need something more, such as the ability to compare several comparisons! Let's be logical about this, and use PHP's logical operators. Suppose for example that you need to know whether $val1 is of lesser value than $val2, and also whether $name1 is of greater value than $name2.

Remember that each comparison expression yields a true or false value. For the record, PHP does not actually possess true or false values, known as boolean data types. Rather, PHP considers the numeric value zero (0), or the string values "0" or empty "" to be false. Any other value, such as 1, or 3, or "cat", is considered to be true. A logical operator compares these true or false values. For example, using PHP's and logical operator:

($val1 < $val2) and ($name1 > $name2)

Because this code fragment is not a full statement, there is no closing semicolon. Rather, we see parentheses grouping two expressions. The lefthand expression will evaluate to the value false, if we assume the example values used in the comparison operator table. The righthand expression will also be false, since "Martin" does not come after "Michael" alphabetically. The and operator will therefore compare the values "false and false". Because this operator returns true only when both expressions are true, the above expression will ultimately return false. That can be hard to follow, so let's look at a summary table.

PHP Logical Operators

Operator Name Description Example Yield
and
And True if both lefthand and righthand expressions are true.
(5>2) and (3>2)

(2>5) and (3>2)
true

false
or
Or True if either lefthand or righthand expression is true.
(5>2) or (2>7)

("h">"a") or (1<3)
true

true
xor
Exclusive Or True if either lefthand or righthand expression is true unless both are true.
("ar">"ac") xor (9>2)

(3==3) xor ("f"=="f")
true

false
!
Not Negates the expression it precedes, true if the expression is not true.
!("small"<"smell")
false

All of these operators can certainly be exhausting!

Just as eye fatigue sets in, a jolt! We're about to string together everything we've learned so far, with the magic of control statements. Things get much more exciting from here on in, for those of us excited by this sort of thing (and who admit it).

 

Control Statements

Programming textbooks refer to a concept called "program flow", which is the order that statements in a program are executed. Typically statements are executed in sequence, first to last. Control statements are used to alter this flow, for instance to execute certain statements only when conditions are met, or to repeatedly execute a series of statements, and so on. If you've any background in another programming language, PHP's control statements will be extremely familiar -- they comprise the standard set featured in most programming and scripting languages.

the "if ... else" statement

A programming classic -- the if ... else statement is used to execute a block of code when a given condition is true. Optionally, you can execute an alternative block of code if the condition is false, or test additional conditions.

if (conditional expression) {
	...code to execute if true...
}
else {
	...code to execute if false...
}

For instance, you might print out a special welcome only if the user submitted the name "Harry":

if ($name == "Harry) {
	print "Hello Harry, my name is also Harry!";
}

Perhaps you set a shipping rate of $5 for total orders below or equal to $25, and $10 for total orders above $25:

if ($total <= 25) {
	$total += 5;
}
else {
	$total += 10;
}

An optional clause, elseif, lets you test alternative conditions before dropping out to the else clause. For example, suppose the shipping rate is $5 for orders of $25 and below, $10 for orders above $25 up to $50, and $15 for orders above $50.

if ($total <= 25) {
	$total += 5;
}
elseif ($total <= 50) {
	$total += 10;
}
else {
	$total += 15;
}

Notice that the elseif clause will only be evaluated if the first condition ($total <= 25) should fail, so we know that $total is at least 26 by the time we evaluate whether it is less than or equal to 50.

the "while" statement

Another classic programming technique is the loop, where one or more statements are executed repeatedly either while or until a certain condition is met. A while loop is probably the simplest loop statement, in PHP or any other language for that matter. Let's count to 100:

$counter = 0;
while ($counter <= 100) {
	print "$counter<BR>";
	$counter++;
}

On each pass, or iteration as they say, through the while loop the condition is tested. As long as the condition remains true, the statements inside the while loop (inside the curly braces which define the "statement block") are executed. Notice that this script will output the numbers 0 to 100, because $counter is not incremented to 1 until the end of the first pass. Also note that if the condition were false initially, the statements inside the while loop would never be executed -- which may be fine, depending on the scenario. The important thing about a loop such as while is that the condition must eventually prove false, otherwise the loop will never end and Very Bad Things may happen -- the computer may lock up, become unresponsive, or the programming language may produce an error. Because we increment $counter on each pass, it will eventually surpass 100, causing the condition to become false.

 

the "do...while" statement

Very similar to while, this variation simply moves the conditional check to the end of the statement block:

$counter = 0;
do {
	print "$counter<BR>";
	$counter++;
}
while ($counter <= 100);

In this case the output would be exactly the same as the output from our while example -- the numbers 0 to 100. The difference is that if the condition proved false on the first pass, the statement block would have been executed at least once, as opposed to never in the case of the while statement.

 

the "for" statement

In many respects the for loop is similar to while, except that all parameters are set forth at the outset. These for statements are often used to repeat a sequence a given number of times. Repeating our example, suppose we want to output a count from 0 to 100:

for ($counter = 0; $counter <= 100; $counter++) {
	print "$counter<BR>";
}

You typically set up three parameters in the for statement, as seen above: the first sets an initial value for the conditional variable; the second specifies the condition to test; the third value modifies the conditional variable on each iteration, or pass through the loop.

gate hopping with "break" and "continue"

You can further modify program flow within a conditional loop using PHP's break and continue statements. The break statement will immediately exit the loop, regardless of conditions, while continue will skip ahead to the top of the loop and the condition test, ignoring any remaining statements in the statement block for the given pass. Let's return to our for statement example, but suppose we want to output only those numbers that are divisble by two.

for ($counter = 0; ; $counter++) {
	if (($counter % 2) != 0) {
		continue;
	}
	print "$counter<BR>";
	if ($counter >= 100) {
		break;
	}
}

Several points are illustrated above. First, we can eliminate the condition from the for statement. This will cause the loop to repeat indefinitely unless there is a break statement somewhere to quit the loop, which is exactly what we've done. We've tested the condition within the statement block, and if the counter surpasses our limit, the break statement is executed. Also notice the first if statement in the statement block: the conditional test compares the value of $counter modulus 2 (the remainder of this division) to zero. If the modulus is not zero, then we know that the counter value was not divisible by two and we issue the continue statement. This will skip the rest of the statements and return to the for, resulting in no output for that pass.

The Function of Functions


A PHP function is a self-contained segment of code which performs a certain task. Often times, but not always, a function will accept parameters -- or values pass to the function which it uses -- and will return a value such as the result of its operations. PHP includes many built-in functions, and they can be categorized under many themes such as math, managing arrays, working with databases, and so on.

For example, the very simple abs function accepts a value parameter and returns its absolute value:

$val1 = -5;
$val2 = abs($val1);

So, $val2 will contain 5.

It is not possible to cover all of PHP's built-in functions as there are so many. But it's also not necessary, since you understand how to work with a function, you need only consult the PHP function reference to browse available functions and their usage details -- what values they accept and what values they return.

We're more concerned here with coding your own functions, which is not an uncommon thing to do. Let's say you would like to code an "is a jerk" function -- it accepts someone's name and simply returns their name in the sentence "so-and-so is a jerk". This is a very mature example to be sure.

function is_a_jerk ($name) {
	return "$name is a jerk!";
}

A function by itself doesn't do anything until it is called. We call our new function from within a statement:

print is_a_jerk("Little Johnny Long Pants");

The function does not itself print the result, it simply returns the result; in the above case, this result is then handed to the print function which triggers the output:

Little Johnny Long Pants is a jerk!

And it's true, he is. Let's consider a more full-figured example of a homegrown function. Imagine that your function accepts a purchase subtotal and a "ship to" state, and must return a final total incorporating the subtotal, applicable shipping, and applicable tax if the state is one where your store has a physical presence (New York, New Jersey, and West Virgina in this example).

function calcFinal ($subTotal,$shiptoState) {
	#First calculate shipping surcharge
	if ($subTotal <= 25) {
		$subTotal += 5;
	}
	else {
		$subTotal += 10;
	}
	
	#Setup array of taxable states with tax rates
	$taxStates = array ("NY"=>0.075,"NJ"=>0.04,"WV"=>0.035);
	
	#Add state tax
	$subTotal *= 1+$taxStates[$shiptoState];
	
	#Done, return results
	return $subTotal;
}

Let's discuss. Our new function calcFinal accepts two parameters, the first being the subtotal and the second being the state (actually, the two letter state abbreviation is what we'll use). Using a variation on our previous if statement, the subtotal is boosted with the shipping surcharge. Next, we create an array where each item key is the two-letter abbreviation for a taxable state and each value is the tax rate multiplier (7.5% for NY, for example).

To add sales tax to our subtotal, we add 1 to the tax multiplier and multiply $subTotal by this value, reassigning the result back to $subTotal. Why? If the state were NJ, the subtotal would be multiplied by 1.04. If the state were FL, the array would return a value of zero since there is no key "FL". We add 1 to this value, therefore multiplying $subTotal by 1, in essence adding no tax.

Finally, the subtotal is returned to the calling expression. The "calling expression" can be any valid expression -- imagine that we use an if statement to determine if the total cost exceeds a given threshold and, if so, offering a discount on a future purchase. Suppose that $purchase holds the current value of items purchased:

if (calcFinal($purchase) >= 1000) {
	print "Congratulations, you have earned 15% off your next purchase!";
}


Functions are a very important way to segregate and enclose specific tasks, especially tasks which may be called upon repeatedly from different statements in a page.

 

Object Orientation

How kind ... we've saved the most challenging for last! Let us close out this welcome (or should we say "wear out"!?) to PHP with a look at objects and the object-oriented programming in PHP. Objects are powerful but sometimes complex structures that have gained great popularity in programming. Before we look at PHP's implementation of objects, let's take a moment to ponder --- what is an object?

An object, in one metaphor, is a container. What does it contain? An object contains variables and it contains functions. That's pretty much it. Like soccer (aka "football"), it sounds a lot simpler than it is!

What might be an object? We could say that the concept of a "car" is an object. A car can possess a number of variables -- a list of colors, model name, model year, manufacturer, wheel size, fuel capacity, invoice price, and so on. We could even imagine that this "car" object has some functions -- a function that determines dealer price based on invoice price and certain features, for instance; or a function that determines fuel efficiency based on the variables of engine type and vehicle weight. The point is, all of this "stuff" is part of the "car" object.

In PHP, as in other object-oriented programming languages, you begin by creating a class, which is like a blueprint of an object. Rather than create a specific car object, for example, we create the outline of what a car object is and can contain.

class Car {
	var $colors;
	var $modelYear;
	var $modelName;
	var $modelMake;
	var $invoice;	
	var $options;

	function dealerPrice ($carObject) {
	#add the values of each option to the invoice price
		$subTotal=0;
		while ( list($option,$cost)=each ($carObject->options) ) {
				$subTotal += $cost;
		}
		return $carObject->invoice + $subTotal;
	}
}


Voila -- we've just created the blueprint, or class, for a car object. The object has four scalar variables and two arrays ($colors and $options), as well as one function. The function simply sums up any values in the $options array and adds the result to the invoice price, resulting in what we're calling the "dealer price" (a pure fiction!).

Blueprint in hand, we can build an actual car object, or what is known as an instance. Suppose we want to create an instance of a new Porsche Boxter:

$boxter = new Car;

We've instantiated the car class, and now own a new but empty $boxter object. To access variables within the object, use the -> constructor:

$boxter->modelYear=1999;
$boxter->modelName="Boxter";
$boxter->modelMake="Porsche";
$boxter->invoice="85000";
$boxter->colors=array ("exterior"=>"red","interior"=>"black");
$boxter->options=array ("turbo"=>5000,"anti-theft"=>2500);

Assuming all values were in place, we could access the boxter object's function to calculate dealer cost:

if ($boxter->dealerPrice($boxter) > 90000) {
	print "Sorry, you can't afford a 
	 $boxter->modelYear $boxter->modelMake $boxter->modelName";
}

Fini

 

"PHP" once stood for "Personal Home Page Tools", but that doesn't make much sense, so it doesn't really stand for anything now. Nonetheless, we've seen that PHP is a fairly full-featured programming language -- in fact, far more full featured than we've even touched on in this introduction. But we've covered the bases, and most of what remains within the PHP language falls under one of the concepts and categories we've thrashed through today.

The PHP web site, http://www.php.net, is the primary source of information and documentation for this language although a few published books have begun to hit the virtual shelves. Spend some time with PHP and see if it's right for you. No single tool is ideal for all projects, and it's always nice to have a bulging toolbelt. That's why PHP is yet another open source success.

 
page d'accueil

contact

 

menu precedent
street fighting
Est-ce ainsi que les hommes vivent ?
Baudelaire Les Fleurs du mal
rfc1869 SMTP Service Extensions
rfc1870 Extension for Message Size Declaration
rfc1939 Post Office Protocol
rfc1957 Observations on Implementations of POP3
rfc2034 Extension for Returning Enhanced Error Codes
rfc2195 IMAP/POP AUTHorize Extension
rfc2449 POP3 Extension Mechanism
rfc2487 Secure SMTP over TLS
rfc2554 Extension for Authentication
rfc822 ARPA Internet text messages
rfc0959 File Transfer Protocol (FTP)
rfc2428 FTP Extensions for IPv6 and NATs
le dernier jour d'un condamne
du cote de chez swann
le joueur
libretto 100
didgeridoo
php
Capability Maturity Model
vcd
histoire de francois m.
le grand secret de toto
sources
1-wire bus
rtos
µC scenix
matrice clavier triangulaire
cables-connecteurs informatiques
format des fichiers S motorola
java
spc statistical process control
codage video couleur
conversion d'unites de surface
conversion d'unites d'energie
conversion d'unites de longueur
conversion d'unites de masse
conversion d'unites de puissance
conversion d'unites de pression
conversion hexa-bin-oct-dec
conversion d'unites de temperature
conversion d'unites de vitesse
calculatrice javascript
cryptographie
yescard
knot tie
Kyusho Atemi-Waza Vital Point Striking Techniques
CRC
source UPS
tcpintro.txt
tcp_ip_tutorial.txt
AWG with current ratings
port parallele
training
le reseau sous DOS
video test
macrovision
Teach Yourself C++
Teach Yourself Java
Teach Yourself C
Java Guide
Applets
Beyond Logic
www.hwb.acc.umu.se
cd

 
moteur de recherche
chercher sur ce site
powered by FreeFind

 

contact

 

FREE, la liberté n'a pas de prix !

<-- precedent ] page d'accueil ] menu precedent ] suite --> ]

derniere mise a jour : dimanche janvier 26, 2003 21:38:01 +0100