• Howdy! Welcome to our community of more than 130.000 members devoted to web hosting. This is a great place to get special offers from web hosts and post your own requests or ads. To start posting sign up here. Cheers! /Peo, FreeWebSpace.net
managed wordpress hosting

Learning PHP: series

ProQ

New Member
Learning PHP: volume 1
You can use any style of programming with PHP, but some things work better than others - I will try to hit all the quirks in this section.


Syntax
You can insert PHP in to a HTML file by typing the first line of code shown here. The second line shows a one-line PHP script that includes a print statement; lines three through six show a multiple-line PHP script:

PHP:
<?php ?>

<?php print("Sup"); ?>

<?php
$message = "Sup";
print($message);
?>

<?php starts PHP code. You can start it anywhere in a HTML page and the code is XML compatible, so always use the syntax <?php. You can also use things like <?, but that does not work with XML. ?> ends the PHP code.

When you include a PHP file within a PHP file, PHP starts reading the included file as HTML, so be sure to start the included file with <?php to get straight into PHP.

Every statement ends with a semicolon, ;, and statement blocks are surrounded with braces, { }, as in:

PHP:
if("a" == "a") {
    print("true");
}

You can leave out the semicolon and braces in certain circumstances, but it makes code hard to understand and leads to mistakes when you modify code.

You can add a commend to the end of a line with // as in:

PHP:
print("true");  // This is a comment.

You can add blocks of comments with /* and */ as in:

PHP:
/* This is a pretty long
comment don't you think?
This can go as far as you want
til you add this -> */

Variables are created by adding $ to the front of a name, and a variable name is case-sensitive. When you add the following two lines to your code, you can print out $a and get the value assigned to $a, not the value assigned to $A:

PHP:
$a = "the contents here";
$A = "different contents here";

Numeric variables do not require quotes. If you use quotes, the variable will be stored as a string, but will be converted to a number when needed as a number.

PHP:
$a = 20;

You can also use names defining logical values, including the following:

PHP:
$a = null;
$b = true;
$c = false;

If, Then, Else
PHP automatically converts between data types, so testing data become more important. Consider the following sections of code:

PHP:
if($a == 0) {
    //do this
}
if($a == 1) {
    //do this
}

In a language with strong typing and a binary field, the code will work perfectly because $a can contain only 0 or 1, and the code has an action for each value. The following code also works for that type of language:

PHP:
if($a == 0) {
    // do this
} else {
    // do this
}

What if another programmer comes along and defines the type as integer? The test using if else will most likely work as intended, because any value over 1 will work as 1. The code using the two if statements will not work, because it will ignore any value greater than 1. What if the same programmer uses a negative number; should -1 be treated like +1 or as a special case? Of there is no logical else, --- a warning message, like this:

PHP:
if($a == 0) {
    // do this
} elseif($a == 1) {
    // do this
} else {
    print("Warning message");;
}

PHP is more liberal with data types, and PHP 4 add the === comparison to let you check values by type; but you still cannot lock in data types, so you have to be careful when interpreting data. Here is an attempt at defining all the possibilities for what you might think is a simple binary field:

PHP:
if(!isset($a)) {
     // some sort of warning
} elseif($a === false) {
    // do this
} elseif($a === true) {
    // do this
} elseif($a == 0) {
    // do this
} elseif($a < 0) {
    // do this
} else {
    // do this
}

First, you have to check that a field exists, because PHP replaces missing fields with a variable of the same name. The next test is to check if a firls is true or false. You have to replace == with ===, because == lets PHP convert numeric and string fields to true or false, whereas === checks that the field is the correct type in the first place.
 
Learning PHP: volume 2
Data is the foundation of your program. If you define your data the wrong way. the program will run, but it will produce the wrong results, which can be absolutely frustrating. PHP has an automatic type conversion that can increase the difficulty of diagnosing problems. Fortunately, PHP4 contributes an extra level of functionality to help you easily test data.

Data Types
PHP lets you define data as strings, integers, floating-point numbers, logical values, and compound mixtures of types. It also provides two sets of special mathematical functions to handle complex math. Here is a simple string:

PHP:
$a = "whatever string";

In the section that follows, you will see how to control data types, which PHP does automatically. In the next tutorial, you will see how to compare and change data.

You will find PHP counting from zero in strings, arrays, and all sorts of functions, so the fifth element of an array is [4]:

PHP:
$fifth = $a[4];

If you get unusual results with PHP data, check all indexes and references, such as the starting character number in the function substr(), in case you counted from 1 where you should have used 0.


Variables
$a is a variable because you can change its value at any time. Constants cannot be changed, and you cannot change a variable in a different scope. Both those conditions ar described late in the tutorial.

Variables have a defined type, such as integer or string; but PHP automatically changes the type when needed, so you can get unexpected results if you make assumptions about a variable's type. A string containing zero characters, as shown in the first line of the following example code, is a string, but can be converted to null, false, or zero. A string containing one character, the number 0, as shown in the second line, can be converted automatically to the value zero, and the value zero can be converted to null or false:

PHP:
$a = "";
$b = "0";

When the data type is important, you have to replace the == operator with the === operator, or use a type-testing function like is_integer(), all of which are described in the following sections. All variabes have a case-sensitive name, which means the variable $proq is different from the variable named $Proq, and both are different from the variable named $ProQ.

Variables have a maximum length, but that length is almost unlimited for a string, and anything else can be converted to a string, thus giving you a length from the string representation. If you are working with numbers and storing the numbers in databases, you will find that the length indicated by a PHP function does not help you work out the space the number will occupy in a database on disk.

Automatic Creation
PHP automatically creates missing variables. In the following code example, the variable name is typed as $metre in the variable definition line, and then as $meter in the print() statement. By default, PHP will create an empty variable $meter for the print statement:

PHP:
$metre = 35;
print($meter);

The isset() function tests if a variable exists, and the unset() function removes a variable completely. unset() might be used in situations where your code uses isset() to check if a variable exists. Be careful about using unset() to indicate a special value, because another person may not use isset() as much as you do.


Constants
A constant gets defined once when you type:

PHP:
define("a", "whatever string");

The define command creates a constant with the name provided in the first parameter and gives the constant the value from the second parameter. In the previous code example, constant a has the value whatever string.

The define command can be used anywhere, and the defined constants have a global scope so your constants are useable inside functions and all sorts of places where variables do not reach. The define command accepts simple data definitions, so it does not handle complex data structures like objects. You could use define to store a name, use the name when you create an object, and then use the defined name to reference the object indirectly, but the resulting application will fry the brain of the next programmer.


Scope
Scope defines where your data is visible. Data defined outside of functions is not visible within functions, and data within functions is not visible outside of functions. This means you can write a function almost independently of the surrounding code. The scope of individual data representations does vary and can be changed: Defined constants cross function boundaries, and ordinary variables can be allowed to cross into a function, if the function has the variables defined as global.

Because PHP automatically creates missing variables, you can be easily confused by variables that are empty when you know they contain data. If you create variable $whiskey in your main code, and then refer to $whisky with a function, $whisky will be empty. You will be confused, and if you are panicking while fixing a broken production application, you will probably be in need of a stiff drink.
 
Learning PHP: volume 3
PHP offers many expressions, operators, control and structure, functions, classes, and objects, and ways of handling data for databases and HTML.


Expressions
Everything in PHP is an expression. Type your age on a line by itself, and you have an expression with your age as the value. Expand the line to "$age = X;" (X being your age) and you have three expressions with your age as the value: your age; $age, which is now set to your age; and the statement as a whole. The following line will print your age because the print() function prints the value of the expression, and the value of the expression is effectively the value assigned to the left hand side of the expression:

PHP:
print($age = 20);  // 20 being the age

PHP allows multiple equal signs and evalues them from right to left. In the following example, $age is set to 20, then $number is set to 20, and then 20 is returned to the print() statement and printed:

PHP:
print($number = $age = 29);

You can slo use the value of an expression in control functions, such as if(), as shown next. Although this example is trivial, you can use the feature by wrapping if() and while() control functions around file and database functions, graphics functions -- and almost every other function -- to control the flow of processing based on what is returned from a function:

PHP:
if($age = 20) {
    print("Age is true");
}

The next example uses mysql_fetch_row() to read a row of data produced by an SQL query on a MySQL database. mysql_fetch_row() returns data until the rows run out, and then it returns false. When false is assigned to $row, false also becomes the value of the whole expression ($row = mysql_fetch_row($query_result)), so false is the value passed to while(). The while() loop loops back to the expression until the expression turns false, and then drops through to the rest of the program. In you program, you would have more than the example print statement within the loop; you would have code to process $row:

PHP:
while($row = mysql_fetch_row($query_result)) {
    print("Another tow from the SQL query");
}

PHP goes to extraordinary lengths to evaluate expressions in useful ways. In a future tutorial on arrays, you will see the following while() structure used to step through arrays. each() returns an element of an array, steps to the next element, and returns false when it hits the end of the array. list() splits the element into key and value, and returns true. While each() is feeding data to list(), while() interprets the expression as true and continues looping. When each() passes false to list(), list() passes false to while(), and the while() loop ends:

PHP:
while(list($key, $value) = each($array))

Early PHP functions did strange things to indicate the end of a process, but PHP functions now almost universally return false at the end of the data, or on encountering an error. That means expressions can differentiate between instances where a function works and returns no data versus instances where a function fails. PHP4's new === operator, explained in the next section, is crucial to handling expressions and functions.

Expressions are mixtures of variables, values, and operators, so there is little more I can tell you without including operators. If you know Perl, you already know enough to make the right guess most of the time and become really frustrated at other times because PHP picks the best out of Perl without picking up all the arcane tricks and traps of it. Some of your favorite tricks may not work, but the majority that do work are the ones understandable by mere humans.


Operators
Start memorizing =, ==, ===, !=, !==, +=, .=, +, -, *, /, $, &, and all the other characters on the keyboard that require strange hand movements. They are your PHP operators. 'http://www.php.net/manual/en/language.operators.php' is a chapter in PHP's official documentation all about PHP operators. Go through it to get acquainted with them because they are very important.
 
Learning PHP: volume 4
This tutorial covers all the statements you use to control the flow through your script, including making decisions with if(), else, and elseif(), and then talks about an alternative syntax. The switch() statement can be a great replacement for long sets of if() statements and is similar to the select statement availbable in other languages. The while() and for() statements let you loop through code based on certain conditions and seem to work like while() and for() in other languages.

The include() and require() statements let you include code from other files, and both work like their equivalents in C. There are a couple of traps to be aware of when using them in PHP, and the new require_once() and include_once() statements help to recude the common problem of including files more than once.

if()
Coding with if() in PHP is similar to coding with if() in other languages. This section will describe the shortcuts for coding with if() in PHP, plus show you some traps to avoid. The next example is a short piece of code to test the value of $a and print "ok" if $a is greater than zero:

PHP:
if($a > 0) {
    print("ok");
}

PHP interprets zero as false, everything greater than zero as true, and everything less than zero as true. Some other languages consider negative numbers to be false, so that can be a trap if you are processing data from other systems. Because PHP automatically converts character data to integer, 0 is also treated as false, as is the zero-length string. If you coded if($a == false), 0 and "" would both produce false results, so you have to code if($a === false).

PHP converts fields straight to logical values, so you can reduce if($a != 0) to if($a) and PHP will convert $a to true or false for if(). You can also code if statements in the form if(!$a) to perform something when $a is false. All these variations can expose you to unintended results, so consider the formal comparison of value and type as in if($a === true) and if($a === false).

The if allows for multiple conditions joined by and, or and structured with parentheses (). Because the conditions are evaluated from left to right, you can check if a variable exists before testing for a value in the variable. The following example will stop at the isset() if $a is not defined, so it will not generate an error message for a missing $a. This is a short example of the code you can use when testing for optional variables that may not exist, such as field from a form:

PHP:
if(isset($a) and $a > 0) {
    print("ok");
}


else
The else statement gives you a great way to cover all values, and it works the same as in all other languages. You use it after an if(), as shown in the following example:

PHP:
if($a == $b) {
    print("equal");
} else {
    print("not equal");
}


elseif()
The elseif() statement lets you step through various conditions using if() statements and is similar to elseif() and else if in other languages:

PHP:
if($a == "hot") {
    print("Turn on air-conditioner");
} elseif($a == "warm") {
    print("Enjoy the weather");
} else {
    print("Turn on heater");
}


switch()
The code example in elseif() can be represented as a multiple selection using switch(). The code based in switch is easier to maintain when there are many possible values and actions. Here is the code from the previous section redone using switch():

PHP:
switch($a) {
    case "hot":
        print("Turn on air-conditioner");
        break;
    case "warm":
        print("Enjoy the weather");
        break;
    default:
        print("Turn on heater");
}

The switch() statement tests a variable or expression, in this case $a, against the expression in the first case statement, "hot", and on a successful comparison, starts executing the code following the case statement. On failure, switch() jumps down to the next case statement and tries another comparison.

The default: statement is equivalent to the else statement with if() - it is the action that will be executed if all the case statements fail. The default: statement is not required, just as an else is not required after an if().

After switch() completes the code in a case statement, switch() keeps on going down the code, running the code unless you have a break statement to jump execution out of the switch(). (Some languages always jump out of their equivalent to switch() without the equivalent of a break, which means you cannot use the equivalent of the next example.) In the previous example, you might want "hot" to both turn on the air-conditioner and display the message about anjoying the weather. All you need to do to accomplish the change is leave out the break at the end of case "hot" as shown here:

PHP:
switch($a) {
    case "":
        print("Turn on air-conditioner");
    case "":
        print("Enjoy the weather");
        break;
    default:
        print("Turn on heater");
}

Sometimes you want multiple values to cause the same action, and many languages allow the equivalent of multiple values on a case statement. PHP requires a case statement for each value, which makes it easier to document each value (with a comment on each line.) In the following example, the programmer likes the weather "hot", and you leaves the air-conditioner off.

PHP:
switch($a) {
    case "hot":
    case "warm":
        print("Enjoy the weather");
        break;
    default:
        print("Turn on heater");
}


while()
When you are reading an array or a file or rows returned from a database, you might like to use while() to control the program execution flow. The only competitor in PHP is for(), but I tend to use while() the most because while() fits better than for() with many PHP functions and constructs.

Many languages give you variations of while() to allow testing of conditions before or after a loop, so you can loop through your code at least once. PHP supplies a do while() statement for those occasions. The following example shows a standard while() loop that will run zero times because $a is already equal to $b. The second part of the code shows the do while() equivalent that runs at least once before testing for $a == $b. The first part prints zero lines, and the second part prints one line:

PHP:
$a = $b = 5;
while($a != $b) {
    print("This will never print");
}


do {
    print("This will print at least once");
} while($a != $b);

The while() loop works extremely well with list() and each() for stepping through arrays, as shown in the next example. The example builds a short array, resets the array pointer to the start of the array, and then uses while() to step through the array. The each() statement returns one array entry at a time, moves the array pointer to the next entry, and returns false at the end of the array. The list() statement takes the data from each() and places the array entry key in the first field, $k, and the array entry value in the second field, $v:

PHP:
$white_crystalline_substance[] = "C12H22O11";
$white_crystalline_substance[] = "C8H10N4O2.H2O";
$white_crystalline_substance[] = "NaCl";
reset($white_crystalline_substance);
print("Warning, the most abused and addictive substances are:");
while(list($k, $v) = each($white_crystalline_substance)) {
    print("<br>" . $v);
}

Note that you do not need to provide an index value when creating an entry for an array; when PHP sees the empty square brackets, PHP automatically uses the next available index number.

When while() steps through the example, it loops through the code three times, once for each entry, and stops when each() returns false:

Code:
Warning, the most abused and addictive substances are:
C12H22011
C8H10N402.H20
NaC1
 
for()
On some occasions, for() is a better choice than while(), such as when you are stepping through a list where you need to count or display a sequence number for each entry. The for() statement accepts three expressions seperated by semicolons and evaluates each expression. Here is a quick example that prints the numbers from one to three:

PHP:
for($i = 1; $i <= 3; $i++) {
    print($i);
}

The first expression is run once at the start of the for() processing and creates your index with the correct starting value. You may leave out the first expression if your index field already exists with the correct value, but remember to leave the semicolon there so for() knows what to do with the next expression.

The second expression is evaluated once per loop through the code at the start of the loop. This couls result in no loops through the code, if the index field has already reached the limit specified in the second expression. You can leave out the second expression, which means for() will loop infinitely, and then break out of the for() loop using a break statement, but this is dangerous, because changes to the code can prevent the process reaching the break statement. If there is a known limit on the passes through the loop, put that in the for() statement, and reserve break statements for breaking out of the for() loop early.

The third expression is evaluated once per loop at the end of the loop. You can leave out this expression, and it can be something like a print statement. You normally use expression three to increment the index field, so that the index field will eventually reach the limit set in expression two, but you might not do this if part of the code in the loop has the effect of incrementing the index. An example might be the use of each(), next(), or mysql_fetch_row, all of which move to the next row or entry in the input.

The following for() example uses the previous while() example and prints the array with items numbered from one upward, the way you might number a top 10 list:

PHP:
print("The most addictive substances are (in order of addictiveness):");
for($i = 0; $i < count($white_crystalline_substance); $i++) {
    $n = $i + 1;
    print("<br>" . $n . " " . $white_crystalline_substance[$i]);
}

Although this code may not be the most elegant-looking solution, it is the most practical, and I will run through the advantages and alternatives. Arrays count from zero, so the for() statement starts with an index set to zero, $i = 0, and runs to one less than the count of the number of elements in the array, incrementing by one, $i++. The code does not use the array pointer, so you do not have to reset the array pointer at the start. The code does not use the key of the array, so it works if entries are deleted from the array, or if the array is sorted in a way that does not resequence the key. In fact, the key could be a number, such as kilograms used per year.

The array is numbered from zero, but the list has to be numbered from one, so the code sets up $n as a discrete field $i + 1. This means that $n can be used in a variety of ways in the print statement, although the example just places $n at the start of the row. This code is easier to change if you need to modify the print formatting.
 
Sorry, I planned on writing up on arrays, but I got tired of writing these long --- tutorials. I think this is a good start for any beginner though. have fun reading :) and go straight to the php manual afterwards.
 
... an addiction:
you can connect 2 strings using .=
PHP:
$a = "this is";
$a .= " a string";
print($a);
this will print out "this is a string"
 
yea that would go under operators but that is such a big topic that I didn't want to get into it.
 
minor annoyance:

If a string does NOT have any variables for php to find, then you should use single quotes in place of double quotes.

PHP:
/* Wrong */

$a = "this is some really long string that has no variables in it 
for php to parse, but php will look anyway because double 
quotes are used";

/* The Following Are Correct */

$a = 'this is some really long string that has no variables in it for php to parse';

$b = 'this is some really long string';
$a = "$b that has no variables in it for php to parse";

$a = $b . ' that has no variables in it for php to parse';

ANY of the above will work, but why make php look for something that isn't there? Improperly double quoting a string may cause performance issues (although slight) in more complex scripts.
 
I'm trying to keep it simple... they can learn that type of stuff on their own when they have a better understanding of php.
 
> I'm trying to keep it simple... they can learn that type of stuff on
> their own when they have a better understanding of php.

IMO, users should learn how to write good php code the first time around, instead of having to change a lot of what they know later on.
 
hey ProQ, what about making tutorials together ? :)
so we could help many people here in less time :madchrist
 
wow so sweet.. i was going to crap in my pan'ts when i saw that site "http://www.proteanart.f2s.com/"
btw that link is death.. if its your.
 
Wouldn't it jsut be easier to direct people to php.net, where they have full docs already, and plenty of tutorials?
Just a thought......
 
Back
Top