53
If you have already learned some JavaScript or Perl, you already have a good run at learning PHP. The letters PHP originally stood for Personal Home Page. It was used as a tracking system for a webpage. This language has grown into a great and powerful tool. The letters PHP now actually mean PHP:Hypertext Processor. (Doesn't sound very original does it?) It means "something to handle data before it becomes HTML". There is an official PHP website located here : http://www.php.net . It is loaded with everything php has to offer. PHP is a server side language. It processes information at the server level like Perl and SSI coding. It is faster, easier, and better to use than any of the alternatives. It will be assumed that you are working with a host plan that offers you PHP4 or you have been able to download and install a PHP module on your own system already. It is also assumed you have a good knowledge of HTML coding. To start things off, here is a simple test script that will check and display some of the host's PHP specifications. Type this in, save it as info.php and upload it to your server area. <html> <head> <title> PHP Test Script </title> </head> <body> <?php phpinfo( ); ?> </body> </html> Afterwards, open your browser and type in the address to view that page. Something like... http://www.yourdomain.com/info.php

Php

Embed Size (px)

Citation preview

Page 1: Php

If you have already learned some JavaScript or Perl, you already have a good run at learning PHP.

The letters PHP originally stood for Personal Home Page. It was used as a tracking system for a webpage. This language has grown into a great and powerful tool. The letters PHP now actually mean PHP:Hypertext Processor. (Doesn't sound very original does it?) It means "something to handle data before it becomes HTML".

There is an official PHP website located here : http://www.php.net. It is loaded with everything php has to offer.

PHP is a server side language. It processes information at the server level like Perl and SSI coding. It is faster, easier, and better to use than any of the alternatives.

It will be assumed that you are working with a host plan that offers you PHP4 or you have been able to download and install a PHP module on your own system already. It is also assumed you have a good knowledge of HTML coding.

To start things off, here is a simple test script that will check and display some of the host's PHP specifications. Type this in, save it as info.php and upload it to your server area.

<html><head><title> PHP Test Script </title></head><body><?phpphpinfo( );?></body></html>

Afterwards, open your browser and type in the address to view that page. Something like... http://www.yourdomain.com/info.php

phpinfo is one of the "built-in" functions that PHP does. There are many others, but this one is a nice one to use to start of as a test.

All working well so far? Good. Continue forth... ... now you don't.

Being a server side language, the PHP coding itself will not be seen when the source code is being viewed. Instead, it's output values will be seen.

If this is entered in the page coding :

Page 2: Php

<?phpprint "Hello World!";?>

This will be seen if someone views the source code : Hello World!

Go back and view the source of that info script you did from the previous page. Looks like A LOT more than what you typed in doesn't it?

Why is this important to know? No real reason, just a tidbit of information. If you need someone to look at your coding to find a problem, you will have to display or send them the actual coding you are using.

Comments areas are wonderful for making notes within your coding no matter what language you are currently using. It helps you organize your coding for editing or reading purposes. Comment areas are not "seen" visibly on the web page. They are simply coding notes.

There are two different types of comment tags. One type will comment out a single line of coding, the other will comment out a block of coding lines.

Single lines of coding may be commented using two slashes // or using a hash # symbol. This type of commenting may be used to comment out a full line, or the remainder of a line.

<?php

// This is an example of commenting.

# This is also an example of commenting.

echo "This text will appear on the web page. <br />";

// echo "This text will not appear.";

echo "Some more example text."; // That prints, not this.

?>

Outcome : This text will appear on the web page.Some more example text.

Commenting more than one line of coding is done using /* and */. Everything between these two tags will be commented. They can be used on a single line to many lines.

Page 3: Php

<?php

echo "This is a commenting test below. <br />";

/*echo "This text will not appear.";echo "Neither will this.";*/

echo "This is a commenting test above.";

?>

This is a commenting test below. This is a commenting test above.

Check out the extension (file type) showing in the address bar right now. It should be showing php002.php. That extension tells the server that this page contains some php coding in it and should be parsed (executed) before the page is displayed. Some host servers may require a slightly different extension such as .php3 which means the server has version3 of the php module loaded for use. Another extension type may be .phtml. Check with your host on which one they require or just test out each type.

The next step is the PHP tags. This will be one more thing to check with your host (or test yourself) to see which one is usable. All PHP coding is contained within a set of PHP tags. <?phpcoding goes here;?>

In many cases, a host will support the "short" version which looks like : <?coding goes here;?>

But if you want to stay with backwards compatability, you should leave the PHP part on the first part. It doens't hurt and still works in the newer versions of PHP.

One more thing to note is the semi-colon. Similar to Javascript, each code line is ended/separated by a semi-colon.

For the rest of these tutorial pages, we will be showing the PHP extension for filenames and using the short version of the tags.

Escape characters are small special functions. Most of them help in the visual presentation of the coding rather than the visual part on the web page.

Page 4: Php

As you have seen, you can easily add in regular HTML coding into the PRINT and ECHO commands. Thus being able to format the webpage contents to your desires. But what about the coding? It seems that a bunch of echo commands will just print out the coding on long continuous lines. Escape characters are here to help.

\n New Line\t Tab\r Carriage Return

The newline command is a very commonly used one when formatting the looks of your coding. The tab command is also helpful for those who prefer to use it throughout their coding for a "neater" layout style. The carriage return may come in handy later on when you are dealing with emails and printed materials.

Before : <?phpecho "This is a test. <br> ";echo "This is another test.";?>

Coding Outcome : This is a test. <br> This is another test.

After : <?phpecho "This is a test. <br> \n";echo "This is another test.";?>

Coding Outcome : This is a test. <br>This is another test.

Escaping is also used for other purposes like having quotes within a quoted area. This was demonstrated on the Print/Echo page.

Operators are the things that assign, compare and combine values.

The equals = symbol is used to assign a value to something.

$StringName = "This value."

The string called $StringName has been assigned (now contains) the phrase This value.

Page 5: Php

Comparison operators will take two values, compare them, and continue on depending on a TRUE or FALSE result. These types of comparisons will be very useful for if/else statements and other loops.

== is equal to!= is not equal to< is less than> is greather than

<= is less than or equal to>= is greather than or equal to

The last batch of operators are known as logical operators. They will usually take two of the comparison operator conditions (above) and compares them to each other.

&& AND|| OR

Sounds a bit confusing doesn't it? Don't worry, it shall all become clear as you go through the various pages following.

Ready to start doing some coding yet?

print and echo are commands used to output information to the visitors screen (on the web page). Both do the same job, so it usually comes down to a matter of personal preference on which one you like to use.

<?phpprint "Hello World! <br />";echo "Hello World!";?>

The output : Hello World!Hello World!

The above example shows both outputs are the same. It also shows that regular HTML tags may be placed within the value areas as well as regular text.

There is a slight difference between print and echo which would depend on how you want to use the outcome. Using the print method can return a true/false value. This may be helpful during a script execution of somesort. Echo does not return a value, but has been considered as a faster executed command. All this can get into a rather complicated discussion, so for now, you can just use whichever one you prefer.

Page 6: Php

Some resources will state that the quoted areas should be within rounded brackets. This is a valid way of coding, but not required.

<?phpprint ("Hello World!");?>

If you need to use quotes within your value area and have them show up on the web page, you will have to "escape" them. This is so the coding does not get confused on which quotes are the real ones and which ones are for display. <?phpprint "Hello from \"another\" World!";?>

Will result as : Hello from "another" World!

Variables are containers. Think of an ordinary box that you put stuff into. That box may have a label on it so you remember what is inside of it. Variables are boxes that you put data information into. They are labeled with names.

Once you have some information in variables, it can be sorted, organized, manipulated, and so forth.

A variable name starts with a dollar $ symbol. After that you can use any combination of higher case letters A-Z, lower case letters a-z, or the underscore character _. Spaces are not allowed.

Variable names are CaSe SeNsItIvE. If you are referring to a variable in your coding, make sure the name matches exactly.$MyVariableName is different from $myvariablename.

Variable names should be easy to understand. Give some thought into the names.$fn or $FirstName or $first_nameWhich one looks more easier to understand and remember?

There are three types of variables. Numbers, Strings, and Arrays.

Number Variables may contain integers (regular positive or negative numbers) or floating-point (decimal) numbers. No fractions, letters, or extra decimals allowed.

$integer_example = 5;$floating_point_example = 365.25;

String Variables are word variables. They may contain number information and other variables. The values of string variables are contained within single quotes ' ' or double quotes " " depending on how you want to use them.

Page 7: Php

$string_example_1 = "This is a test.";$string_example_2 = 'This is another test.';$string_example_3 = "5";$string_example_4 = "The value is $integer_example.";$string_example_5 = 'The value is $integer_example.';

The difference between single and double quotes is : Single quotes will print out the exact value of the string as is. Double quotes will transfer variable values into place before printing.

echo "$string_example_4 <br />";echo "$string_example_5";

Outcome : The value is 5. The value is $integer_example.

Arrays are groups of variables. These will be discussed in more detail on their own page.

Numbers can be added, subtracted, multiplied, divided, put into variables, formatted, and so on.

<?php$number = 10;$number = $number + 1;echo "$number";?>

Outcome : 11

Math in PHP follows the same precedence rules as regular math. BEDMAS. From most important to least important is :Brackets Exponents Division Muliplication Addition Subtraction

<?php$first_number = 10 - 4 / 2;$second_number = (10 - 4) / 2;echo "$first_number <br />";echo "$second_number";?>

Outcome : 8 3

Page 8: Php

A simple shortcut method may be used to add or subtract 1 from a number.

<?php$number = 10;$number++;    // that is the same as saying $number=$number+1;echo "$number";?>

Outcome : 11

Can you guess what you would put to decrease a number by one? For those who are having a brain fuzzy :

<?php$number = 10;$number--;    // that is the same as saying $number=$number-1;echo "$number";?>

Outcome : 9

We will start with a bit more complex outcome for numbers :

<?php$first_number = 10;$second_number = 3;$div_value = $first_number / $second_number;echo "$div_value <br />";$total_sum = $first_number + $second_number;echo "$total_sum";?>

Outcome : 3.3333333333333 13

To format numbers, you will have to switch from an ECHO command to a PRINTF command.

<?php$first_number = 10;$second_number = 3;$div_value = $first_number / $second_number;printf ("%01.2f", $div_value);

Page 9: Php

echo "<br />";$total_sum = $first_number + $second_number;printf ("%01.2f", $total_sum);?>

Outcome : 3.3313.00

So how does this PRINTF work? The printf command tells the server to format the following variable in "this" way.

The important settings are between the % and the f. The first digit inserts zeros for extra padding which depends on the second digit. The second digit states how many padding spaces are going to appear before the decimal space. In the above example, the second digit is set at 1 so there will be at least one. Try setting it to 5 and see what happens :

<?php$first_number = 10;$second_number = 3;$div_value = $first_number / $second_number;printf ("%05.2f", $div_value);?>

Outcome : 03.33

The third digit states how many decimal places are going to be shown after the decimal. Try setting it to 4 :

<?php$first_number = 10;$second_number = 3;$div_value = $first_number / $second_number;printf ("%05.4f", $div_value);?>

Outcome : 3.3333

ROUND is used to round a number up or down to the nearest number. 5 and over will roundup, 4 and under will round down.

<?php$number_1 = 10.356;

Page 10: Php

$rounded_number_1 = round($number_1);echo "$rounded_number_1 <br />";$number_2 = 10.5367;$rounded_number_2 = round($number_2);echo "$rounded_number_2";?>

Outcome : 10 11

To specify a certain number of decimal places, add in a comma and number after the variable (or number) in the brackets. The last number will be rounded up or down depending on the next decimal number.

<?php$number_1 = 10.356;$rounded_number_1 = round($number_1,1);echo "$rounded_number_1 <br />";$number_2 = 10.5367;$rounded_number_2 = round($number_2,2);echo "$rounded_number_2";?>

Outcome : 10.4 10.54

The absolute function will create the positive effect to a number. If it is a positive number to start, it will remain positive. If it is a negative number to start, the result will be a positive number.

<?php$number_1 = abs(35);$number_2 = abs(-35);echo "$number_1 <br />";echo "$number_2";?>

Outcome : 35 35

Page 11: Php

Creating a random number takes two commands called srand and rand. srand is a preparation command for rand. It helps rand create a truely random number. rand itself creates the random number.

<?phpsrand ((double) microtime( )*1000000);$random_number = rand( );echo "$random_number";?>

551812185

If you refresh this page a few times, you will notice the number in the above example will change each time. The value in the srand command is a number mixer, which is then passed into the actual rand command.

To make a random number within a specific range, you can add the number range in the rand command brackets. This example will find a number between 0 and 10 :

<?phpsrand ((double) microtime( )*1000000);$random_number = rand(0,10);echo "$random_number";?>

0

Connecting strings together is known as concatenation. The operator to use with this is the period.

$NewString = $string1 . $string2;

The value of $NewString is the combination of $string1 and $string2. This is not addition like in math. This is taking the value of $string2 and plunking it onto the end of $string1.

<?php$string1 = "This is an example";$string2 = "of connecting strings.";$NewString = $string1 . $string2;echo "$NewString";?>

This is an exampleof connecting strings.

Page 12: Php

Hmmm... that doesn't quite look right. There should be a space between the words example and of. Let's add in a space on the connecting code line :

$NewString = $string1 . " " . $string2;

This is an example of connecting strings.

So you can add strings, direct quoted data, and so forth together. Some "real world" example of using this may be to combine a $FirstName and $LastName into one string. There could be many other uses as well.

There are two methods to extract information from a string. The first is using a token method. This will take a specified string and find all the information from the start of the string until a specified character is reached.

<?php$bigstring = "BigBad Wolf";$firstpart = strtok($bigstring," ");echo "$firstpart";?>

BigBad

The strtok searched from the start of $bigstring until it found the first specified character. In this case, a space character. That value now belongs to the string called $firstpart. The search character could be a comma, letter, number, whatever. One more example for this command :

<?php$bigstring = "Wolf,BigBad";$firstpart = strtok($bigstring,",");echo "$firstpart";?>

Wolf

The next way to search a string is to use a substring method. This will take an index position of a string and take the specified number of characters after that position.

Wait, what? Index position?? Index position is a number. It specifies which character to start looking at in the string. The first character, second, third, and so on... One thing to remember though, PHP coding starts counting from zero, not one.

Page 13: Php

$bigstring = "BigBad Wolf";

The index position 2 in the $bigstring value is g. B is at zero, i is at one, g is at two.

Now that you can specify a starting point, the next step is to specify the number of characters to view (including and) after that point. This example will show substr in action starting at position 7 and taking 4 characters. If it works correctly, the example string will hold a value of Wolf.

<?php$bigstring = "BigBad Wolf";$example = substr($bigstring,7,4);echo "$example";?>

Wolf

One more command to learn for now is strlen which stands for string length. There will be times when you don't know how long a string may be considering it often comes from a different source such as a database of form input. This command will help you determin how long a string is.

<?php$bigstring = "BigBad Wolf";$stringlength = strlen($bigstring);echo "The length of the string is $stringlength.";?>

The length of the string is 11.

The example shows that $bigstring contains 11 characters. If you want to use this information in a substr command, remember to subtract one from the value. Remember, the substr starts counting from zero. The strlen command starts counting from one.

Yes, that is all a bit tricky, but once you get the hang of it, it may become rather useful.

if may be a small word, but it carries a big job. It is a very useful tool in creating a php script.

<?phpif (condition) {   do this block of coding;   if the condition carries a true value;

Page 14: Php

   }?>

This would be a good time to re-read the operators page. They are commonly used in the condition statement to find the true or false values.

The block of coding within an IF statement will only be looked at IF the condition has a true value. The block of coding will be ignored if the condition has a false value.

<?php$test = 42;if ($test > 40) {   echo "Yes, $test is greater than 40.";   }?>

else is used in the situations when you want perform a block of coding if the IF CONDITION has a false value. This is an optional thing you can use.

<?phpif (condition) {   do this block of coding;   if the condition carries a true value;   } else {   do this block of coding;   if the condition carries a false value;   }?>

Sometimes you only need the IF statement to execute a block of coding upon a certain condition. Other times, you will want to execute either this or that block of coding depending if the condition value is true or false. That is when ELSE comes into play.

<?php$test = 32;if ($test > 40) {   echo "Yes, $test is greater than 40.";   } else {   echo "No, $test is less than 40.";   }?>

elseif is an extra conditional test within an IF statement. It's like doing a second IF test for a true

Page 15: Php

or false value. The block of coding in an ELSEIF area will be executed only if the condition value of the IFELSE is true. This part goes after the IF and before the ELSE areas.

<?phpif (condition) {   do this block of coding;   if the condition carries a true value;   } elseif (different condition) {   do this block of coding;   if the elseif condition carries a true value;   } else {   do this block of coding as a default;   if all above conditions carried a false value;   }?>

There could be many ELSEIF statements listed depending on the situation. For our example, we put in only two.

<?php$test = 32;if ($test > 40) {   echo "Yes, $test is greater than 40.";   } elseif ($test > 35) {   echo "Yes, $test is greater than 35.";   } elseif ($test > 30) {   echo "Yes, $test is greater than 30.";   } else {   echo "No, $test must be less than 40 and 35 and 30.";   }?>

For those of you who want to see the result : Yes, 32 is greater than 30.

Changing the value of $test to 22 will result as : No, 22 must be less than 40 and 35 and 30.

switch/case is very similar or an alternative to the if/elseif/else commands. The switch command will test a condition. The outcome of that test will decide which case to execute. Switch is normally used when you are finding an exact (equal) result instead of a greater or less than result.

<?phpswitch (condition) {

   case "value1" :

Page 16: Php

   block of coding;   if the condition equals value1;   break;

   case "value2" :   block of coding;   if the condition equals value2;   break;

   default :   block of coding;   if the condition does not equal value1 or value2;   break;

   }?>

There can be many cases listed. For example purposes, we only show two. There are a few things happening at the same time here :

1. The switch condition is examined and a value is found.2. The condition value is passed through the cases.3. If the value matches a case value, the code in that block is executed.4. If the value does not match any of the case values, the default section is executed.5. Once a block of coding is finished, the BREAK command is used to jump out of the switch/case area.

<?php$test = 32;

switch ($test) {

   case "40" :   echo "The value equals 40.";   break;

   case "32" :   echo "The value equals 32.";   break;

   default :   echo "The value is not 40 or 32.";   break;

   }?>

Page 17: Php

And the result : The value equals 32.

while is a loop. It will execute a block of coding for a specified amount of times.

<?phpwhile (condition) {   do this block of coding;   while the condition carries a true value;   }?>

Time for a quick example : <?php$test = 0;while ($test < 10) {   echo "$test is less than 10. <br />";   $test++;   }?>

Example results : 0 is less than 10.1 is less than 10.2 is less than 10.3 is less than 10.4 is less than 10.5 is less than 10.6 is less than 10.7 is less than 10.8 is less than 10.9 is less than 10.

At the end of each block execution, the while condition is tested again. If the condition holds a true value, the code block will be executed again. And so forth until the condition results as false. In this case, once $test equalled 10, the condition was false and the loop was broken.

If the value of the condition is false to begin with, the code block contained in the loop area is ignored. It will only be seen WHILE the condition is true.

do while is very similar to the above WHILE loop. It's main difference is the code block will be executed at least once before the condition statement is tested for a true or false value. If it is a

Page 18: Php

true value, the loop will happen as before. If it is a false value, it will not perform the loop area any further.

<?phpdo {   do this block of coding;   while the condition carries a true value;   } while (condition);?>

Here is that example again : <?php$test = 0;do {   echo "$test is less than 10. <br />";   $test++;   } while ($test < 10);?>

And the result : 0 is less than 10. 1 is less than 10. 2 is less than 10. 3 is less than 10. 4 is less than 10. 5 is less than 10. 6 is less than 10. 7 is less than 10. 8 is less than 10. 9 is less than 10.

One of the main problems of using a DO WHILE loop, is that first execution. Try changing the value of $test to 15 : 15 is less than 10.

Not exactly correct is it? That happened because the loop was exectued for the first time before the condition was tested to be true or false. There very well may be times to need this effect. Just be sure which direction you want your loops to go in.

for is a loop. It will loop through a block of coding for a specified amount of times. The WHILE loop on the previous page used a counter method (control) to determine its looping times. The for loop has it's counter control in the condition area.

Page 19: Php

for (initial expression; condition test; closing expression){   block of coding here;   }

initial expression is assigning a value to start with (usually the start of a counter).condition test tests the current status to determin if the loop should happen or not.closing expression affects the current status (usually increasing or decreasing).

An Example : <?phpfor ($test=0; $test<10; $test++){   echo "$test is less than 10. <br />";   }?>

Results : 0 is less than 10. 1 is less than 10. 2 is less than 10. 3 is less than 10. 4 is less than 10. 5 is less than 10. 6 is less than 10. 7 is less than 10. 8 is less than 10. 9 is less than 10.

What's happening :1. The variable $test starts with a 0 value.2. The condition test checks if $test has a value less than 10.3. If the value is true, do the loop. If false, skip out of the loop.4. After each loop is completed, increase the variable $test by one.5. Return to step 2 and continue until the condition test becomes false.

Arrays are a bunch of variables taking up the same space.

Think of a fruit pantry. You have a box of apples, a box of oranges, and a box of bananas. The apple box has a label saying "box1", oranges are "box2" and bananas are "box3".

$box1 = "apples";$box2 = "oranges";$box3 = "bananas";

Those are now named variables containing values. The fruit pantry (or closet or fridge or

Page 20: Php

whatever you want to put these boxes into) will be the array. An array is a container that holds variable containers.

$pantry[ ];

The following tutorial pages will show how to create and use arrays.

The first step in creating an array is to specify a variable name as an array. <?php$pantry = array( );?>

The next step is to add in the contents for the array to hold. <?php$pantry = array(   "apples",   "oranges",   "bananas"   );?>

The listed values in an array field is separated by commas.

Now you have to remember how to count. Huh? You mean like 1 2 3 and so on? Yes, exactly. That is how an array will INDEX its contents except for one minor part... it starts counting at zero instead of one. Apples is at index 0, oranges is at index 1, and bananas is at index 2.

As you have seen on the previous page, an array usually looks like this when you are actually working with them : $pantry[ ];

The square brackets hold an index value. If you wanted to print out oranges, the index value of 1 could be entered in the square brackets. <?phpecho ("$pantry[1]");?>

That is ok for the most part, but some people like to start counting at one. To create this effect, we can add our own index values. <?php$pantry = array(   1 => "apples",   2 => "oranges",   3 => "bananas"

Page 21: Php

   );?>

The list is still comma separated, but now there is a new set of values to use as the INDEX. In a normal equation, the => symbol represents "equal to or greater than". In arrays, it is used to assign values to an index. To print out the value of oranges now would look like : <?phpecho ("$pantry[2]");?>

Label names with values can also be used in arrays. This option looks the most similar to having actual variables being contained within the array.

<?php$pantry = array(   "box1" => "apples",   "box2" => "oranges",   "box3" => "bananas"   );?>

Then finding the contents of box2 would look like : <?phpecho ("$pantry[box2]");?>

Once you have an array created, the next usual step is to add items (values) into it. The equals sign is used to do this. Here is our example array started :

<?php$pantry = array(   1 => "apples",   2 => "oranges",   3 => "bananas"   );?>

There are two ways of adding values into an array. The first way is to leave the square brackets blank.

<?php$pantry[ ] = "potatoes";$pantry[ ] = "bread";?>

The above will add the new items onto the end of the current array list. To replace a specific

Page 22: Php

array element to a new value or to add values into a specific spot, the index may be used in the square brackets.

<?php$pantry[4] = "potatoes";$pantry[5] = "bread";?>

In both cases, the values will be added to the end of the current array. Replacing one of the array values is done the same way. Lets replace the potatoes with tomatoes :

<?php$pantry[4] = "tomatoes";?>

Merging two arrays together is a one step command called array_merge.

First we will start with our original pantry array and a second array :<?php$pantry = array(   1 => "apples",   2 => "oranges",   3 => "bananas"   );$pantry2 = array(   1 => "potatoes",   2 => "bread",   3 => "tomatoes"   );?>

Now to combine them into one... <?php$pantry_food = array_merge ($pantry, $pantry2);?>

The newly formed array called "pantry_food" will contain all 6 entries from the two arrays. The index for pantry_food will appear from 0 to 5. Visually, it would look like this... $pantry_food[0] = "apples";$pantry_food[1] = "oranges";$pantry_food[2] = "bananas";$pantry_food[3] = "potatoes";$pantry_food[4] = "bread";$pantry_food[5] = "tomatoes";

Page 23: Php

Counting the number of elements in an array uses a command called count.

First we will start with our original pantry array :<?php$pantry = array(   1 => "apples",   2 => "oranges",   3 => "bananas"   );?>

Now to count how many elements are in this array... <?php$total_elements = count($pantry);echo "There are $total_elements elements in the array.";?>

This will produce the result : There are 3 elements in the array.

You can access an individual element in an array by calling a specific index value.

<?php$pantry = array(   1 => "apples",   2 => "oranges",   3 => "bananas"   );$findit = $pantry[2];echo "The value of findit is $findit.";?>

Gives the result showing : The value of findit is oranges.

To run through an entire array, a loop would be used with the each command.

<?php$count_total = count($pantry);for ($counter=0; $counter<$count_total; $counter++){$line = each ($pantry);echo "$line[key] $line[value] <br />";}?>

Page 24: Php

Here's the breakdown :The total number of elements is calculated.The FOR loop starts a counter set to zero.The FOR loop will continue as long as the counter value is less than the number of entries in the array.The counter is increased by one after each loop is completed.$line is a temporary array variable. It will hold two values per loop. One value being the KEY or index and the second value being the VALUE of that specific KEY.The echo command prints out the current values.

And the result is : 1 apples 2 oranges 3 bananas

This is a function that I find very useful while working with arrays, especially for filtering certain items.

Usage: in_array(search word, array)

This is useful because when you want to find a value easily, you can use this. Also, it is useful for maybe blocking certain things, check this example:

<?php$fruit = array("apple","orange","strawberry");if(in_array("apple", $fruit)){echo "Apple is in the array";}else{echo "Apple is not in the array";}?>

This would return "Apple is in the array"

Another use for this would be blocking things, such as IP addresses from accessing your site, here is an example:

<?php$blocked = array("192.168.1.11", "192.168.1.12", "192.168.1.13");$ip = $REMOTE_ADDR;if(in_array($ip, $blocked)){

Page 25: Php

echo "You have been banned from this site";}else{//normal page code here}?>

If the person has the IP address of any of the three in the array, they will receive the banned message, otherwise, they will see the normal content that everyone else will see.

Tutorial contributed by : Jeremy Tymes

Sorting means organizing a bunch of values in alphabetical or numerical order. PHP can be used to sort an array by it's keys or values. The result can keep the corresponding key/value with the original value/key or replace them. That sounds a bit confusing, so here are the examples to sort it out (couldn't resist the pun).

Here is a sample array to start things off : <?php$pantry = array(0 => "tomatoes",1 => "oranges",2 => "bananas"3 => "potatoes",4 => "bread",5 => "apples");?>

Use the sort command to sort the values with no regard to the keys. The values only will be changed.

sort($pantry);

The pantry array now looks like this...0 apples 1 bananas 2 bread 3 oranges 4 potatoes 5 tomatoes

Page 26: Php

The values have changed places into alphabetical order while the keys remain in the same order.

To sort the values in reverse order with no regard to the keys, the rsort command is used.

rsort($pantry);

The pantry array now looks like this...0 tomatoes 1 potatoes 2 oranges 3 bread 4 bananas 5 apples

The values have changed places into alphabetical order while the keys remain in the same order.

To sort the values and keep the corresponding keys, the asort command is used.

asort($pantry);

The pantry array now looks like this...5 apples 2 bananas 4 bread 1 oranges 3 potatoes 0 tomatoes

A similar sorting with keys technique can also be done in the reverse order using the arsort command.

arsort($pantry);

The pantry array now looks like this...0 tomatoes 3 potatoes 1 oranges 4 bread 2 bananas 5 apples

Page 27: Php

To sort the keys and keep the values, the ksort command is used.

ksort($pantry);

The pantry array now looks like this...0 tomatoes 1 oranges 2 bananas 3 potatoes 4 bread 5 apples

In this case, it remains the same as the original array considering the keys were already in numerical order.

To sort the keys and keep the values in reverse order, the krsort command is used.

krsort($pantry);

The pantry array now looks like this...5 apples 4 bread 3 potatoes 2 bananas 1 oranges 0 tomatoes

The shuffle command is used to randomly reorganize the values of an array. The keys remain the same.

shuffle($pantry);

The pantry array now looks like this...0 bread 1 apples 2 tomatoes 3 potatoes 4 oranges 5 bananas

If you reload this page, the above result will appear different.

Page 28: Php

The array_push( ) command is used to add a new element to the end of an array. It will look at the current array, find the highest known index number, and add the new item to the array.

<?php$pantry = array(1 => "tomatoes",0 => "oranges",4 => "bananas",3 => "potatoes",2 => "bread");

array_push($pantry, "apples");?>

Even though the array was declared out of order, the push command will find the highest index number and assing the next one to the new array entry. Thus $pantry[5] carries the value of apples. This command works exactly the same as adding in a new value normally with $pantry[]="apples"; This array now lists as...

orangestomatoesbreadpotatoesbananasapples

The array_pop( ) command is used to delete the last found array entry. This is not looking for the highest index number, but rather the last physical entry for the array.

<?php$pantry = array(1 => "tomatoes",0 => "oranges",4 => "bananas",3 => "potatoes",2 => "bread");

array_pop($pantry);?>

Even though 4 is the highest index number and should be condidered as the last item in the array, it is the number 2 index value that will be deleted as it is the last physical entry shown for the array. The index numbers will remain the same, but the value will become empty. This array now lists as...

Page 29: Php

oranges tomatoes

potatoes bananas

Exploding and imploding refers to changing between a string and an array. You can take a specific string and create an array out of the words or vice versa.

Using the explode command will create an array from a string.

Here is a sample string to start things off : <?php$pantry = "tomatoes,oranges,bananas,potatoes,bread,apples";?>

Now you have to figure out a common seperator element. In this case it is a comma seperating each word. In a normal sentence, it could be specifed as a space.

Time to explode this string into an array... <?php$pantry = "tomatoes,oranges,bananas,potatoes,bread,apples";$pantry_food = explode(",",$pantry);?>

The array called $pantry_food now contains 6 elements. The array keys range from 0 to 5 and contains the values of tomatoes to apples. Doing a quick array print out : <?php$count_total = count($pantry_food);for ($counter=0; $counter<$count_total; $counter++){$line = each ($pantry_food);echo "$line[key] $line[value] <br />";}?>

results as : 0 tomatoes 1 oranges 2 bananas 3 potatoes 4 bread 5 apples

So exploding breaks the data apart, imploding brings the data together. The implode command

Page 30: Php

will take the data from an array and assemble it into a single string.

We will use the newly created array from above and implode it into a new string. <?php$new_pantry = implode(" ",$pantry_food);?>

Imploding uses a separator element as well. In this case, it adds the separator between each of the array elements when it creates the new string. The above example is using a space this time.

The new string : <?phpecho "$new_pantry";?>

Has the value of : tomatoes oranges bananas potatoes bread apples

Regular expressions are matching patterns. First you tell the script what you want to search for and where, then it will try to find it. If the search is a success, a TRUE value will appear. If the search is a failure, a FALSE value will appear.

A pattern is what you are looking for in a specific area. It can be a word, a letter, whatever. For our examples, we will use the letter z.

There are two commands to use for searching. ereg for doing a case sensitive search (for specifically a lower or upper case letter) or eregi for doing a case insenitive search (searching for either a lower or upper case letter).

The ereg command takes two properties. One for the pattern to search for, the second for the search area.

ereg<?php$pattern = "z";$search_area = "My car goes ZOOM.";$search_result = ereg($pattern,$search_area);

if ($search_result){// print this if there is a true result.echo "Success, the pattern was found!";} else {// print this if there is a false result.echo "Failure, the pattern was not found!";}?>

Page 31: Php

result : Failure, the pattern was not found!

eregi<?php$pattern = "z";$search_area = "My car goes ZOOM.";$search_result = eregi($pattern,$search_area);

if ($search_result){// print this if there is a true result.echo "Success, the pattern was found!";} else {// print this if there is a false result.echo "Failure, the pattern was not found!";}?> result : Success, the pattern was found!

Metacharacters are special add-on things for doing a search. Keeping the z as our example to search for, here is a list of different metacharacters you can use...

^z searches for a part that begins with z.z$ searches for a part that ends with z.z+ searches for at least one z in a row.z? searches for zero or one z.(yz) searches for yz grouped together.y|z searches for y or z.z{3} searches for zzz.z{1,} searches for z or zz or zzz and so on...z{1,3} searches for z or zz or zzz only.

Other metacharacter type searches include...

. searches for ANY character or letter.[a-z] searches for any lowercase letter.[A-Z] searches for any uppercase letter.[0-9] searches for any digit 0 to 9.\ escapes the next character.\n new line.\t tab.

Page 32: Php

The escape \ is used if you want to include a special character in the search itself. These are ^.[]$()|*?{}\. Since these characters in used as search commands, if you need to search for that character itself, you need to put the escape in front of it. For example... if you need to search for a dollar sign, it would look like \$ instead of just the dollar sign. The dollar sign by itself would create a search that ends with something.

These search parameters can be used alone or in combinations. A real world example would be to look at an email address and check to see if it seems to be valid or not.

A seemingly valid email address ([email protected]) contains :1. An unknown amount of letters or numbers. .+2. The @ symbol. @3. An unknown amount of letters or numbers. .+4. A period.\. (Remembering to escape it.)5. Some ending characters. .+

This will not actually check to see if the email itself is a working one, but at least it will check to see if it qualifies to be an email address to begin with.

<?php$value1 = "[email protected]";$value2 = "[email protected]";$value3 = "here@therecom";

$search_pattern = ".+@.+\..+";

$result1 = eregi($search_pattern,$value1);$result2 = eregi($search_pattern,$value2);$result3 = eregi($search_pattern,$value3);

if ($result1) {echo "one is true. ";} else {echo "one is false. ";}if ($result2) {echo "two is true. ";} else {echo "two is false. ";}if ($result3) {echo "three is true.";} else {echo "three is false.";}?>

one is true. two is true. three is false.

Using these metacharacters and a pair of (parentheses) you can create a number of different and complex search patterns. Here are some examples of different search patterns :

abc{3} searches for abccc(abc){3} searches for abcabcabcon|off searches for onff or ooff(on)|(off) searches for on or off

Page 33: Php

Character classes are a defined set of characters. PHP holds some pre-defined classes for expressions :

[[:alpha:]] any letter[[:digit:]] any digit[[:alnum:]] any letter or digit[[:space:]] any white space[[:upper:]] any upper case letter[[:lower:]] any lower case letter[[:punct:]] any punctuation mark

Classes are created by putting a set of characters within the [square] brackets. Searching for a vowel may be done by using [aeiou] for example. The search will take each letter and do a search for it in the specified area.

Using a dash inside a class is a shortcut to specify "between". Using [a-f] will do a search for any lowercase letter between a to f.

Combinations can also be entered in classes. Using [a-zA-Z] will do a search for any lowercase or uppercase letter. This would also create the same result as using the [[:alpha:]] class in this example.

The ^ symbol has a different effect inside the square brackets. It will do a search that does not include the pattern specified. Using [^z] searches for any character other than lower case z.

Using this new information, you can revise the email address checker script like so... <?php$value1 = "[email protected]";$value2 = "[email protected]";$value3 = "here@therecom";$value4 = "[email protected]";$value5 = "[email protected]";

$search_pattern = "^([0-9a-z]+)([-._0-9a-z]+)@([-._0-9a-z]+)(\.[a-z]{2,3}$)";

$result1 = eregi($search_pattern,$value1);$result2 = eregi($search_pattern,$value2);$result3 = eregi($search_pattern,$value3);$result4 = eregi($search_pattern,$value4);$result5 = eregi($search_pattern,$value5);

if ($result1) {echo "one is true. ";} else {echo "one is false. ";}if ($result2) {echo "two is true. ";} else {echo "two is false. ";}if ($result3) {echo "three is true. ";} else {echo "three is false. ";}if ($result4) {echo "four is true. ";} else {echo "four is false. ";}

Page 34: Php

if ($result5) {echo "five is true. ";} else {echo "five is false. ";}?>

Results : one is true. two is true. three is false. four is false. five is false.

Here is the breakdown of the search pattern... ^([0-9a-z]+) The value should start with at least one number or letter.

([-._0-9a-z]+)The next characters should be at least one dash, period, underscore, number, or letter.

@ The @ symbol required in any email address.([-._0-9a-z]+) Another set of characters at least one dash, period, underscore, number, or letter.(\.[a-z]{2,3}$) The value should end with the period then either two or three letters.

We did not have to enter the capital letters for searching because the eregi is not case sensitive.

The first two samples are true as they contain all the correct elements. The third sample is false as it is missing the period. The fourth sample is false as it contains an ending more than 3 letters. The fifth sample is false as it contains an ending of less than 2 letters.

This was a really complicated search pattern, but taking it one step at a time, you can see how it works. This also shows you can create a very simple or elaborate search pattern depending on your needs in a script.

Please note : The dash is used at the start of the patterns so it is not viewed as a range character. When the period is contained within the square brackets, it is viewed as an actual period and does not need to be escape backslashed. (Thank-you to Ryan Quigley for correcting our error previously seen on this page.)

As seen on the previous tutorial pages, ereg( ) and eregi( ) are used to find patterns. Taking this to the next level will allow you to find a pattern and replace it with a new value. This is using ereg_replace( ) and eregi_replace( ). The i has the same effect as before, case insensitive.

The replace command looks like this : eregi_replace(pattern,replacement,search_area);

Very similar to the normal eregi command only it has an extra parameter in the middle.

A replacement can be used for many different uses such as...1. Taking an entered URL and making it a clickable one.2. Replacing a text smilie into an image one.

Page 35: Php

3. Replacing bad words with *@!%.

Most of these examples would be taking some user input from a form and processing it to a webpage or email. We'll do an example using the smilies.

On the form page<form method="post" action="changeit.php"><input type="text" name="entry"><input type="submit" value="submit"></form>

changeit.php<?php$pattern = ":\)";$replacement = "<img src=\"smilie.gif\">";$entry = ereg_replace($pattern,$replacement,$entry);echo "$entry";?>

Here is the test in action. If you enter :) into the text box, it will appear as a smilie image in the second cell. The current page will reload upon submit, so you will have to scroll down to see the result here.

A function is a block of commands or instructions. If you have a specific block of commands that you are going to be using over and over again, this may be a very useful tidbit to use.

function function_name ( ) {    some PHP commands;    some PHP commands;}

The word function lets the coding know that this set of commands will be executed when they are called upon by the following function name.

The function_name, like variable names, should be descriptive. Stay away from using spaces. Use_underscores_instead. The parentheses can be used to pass information into the function.

The commands in the function are normal PHP commands. There can be one or many. As usual, they all end with a semi-colon.

Calling a function is simply done by using it's function name as a command. Most functions are stored at the start of the page coding so they can be found and edited easily.

Somewhere near the top of the page coding :

Page 36: Php

<?phpfunction printit( ){echo "This will print second.<br>";}?>

Later in the page coding : <?phpecho "This will print first.<br>";printit( );echo "This will print third.";?>

Result : This will print first.This will print second.This will print third.

Arguments. No it's not about two functions getting into a fight. An argument is information being passed from the coding into the function.

The parentheses in the function area will hold varables. These variables will catch the information being sent into the function. Each variable is seperated by a comma.

function function_name ($variable1,$variable2,$variable3) {    some PHP commands;    some PHP commands;}

When the function is called from the coding area, it will have values in its parentheses area which will be passed into the function. The values can be a variable (which holds a value) or a quoted value itself.

function_name ($variablename,"MyName",$anothervariable);

The information passed into the function goes in from left to right.The value of $variablename will be passed into $variable1.The value of "MyName" will be passed into $variable2.And the value of $anothervariable will be passed into $varaible3.

So what happens if the function variable name is the same as the passed variable name but in a different order?

function function_name ($variable1,$variable2,$special) {    some PHP commands;    some PHP commands;

Page 37: Php

}

function_name ($special,"MyName",$anothervariable);

The value of $special from the coding will be passed into $variable1.The value of "MyName" will be passed into $variable2.And the value of $anothervariable will be passed into $special of the function.

What happened? Why didn't the two variable names match up with eachother? The function variables are just temporary storage spots which will be used inside the function only. They don't care about "outside" variable names. They just gather information from left to right and do their function commands.

Example : <?phpfunction print_it_out($first_part,$second_part,$third_part){    echo "$first_part $second_part $third_part";}

$part3 = "HTMlite site.";$part1 = "Welcome";$part2 = "to the";

print_it_out($part1,$part2,$part3);?>

Results : Welcome to the HTMlite site.

What you may want to do however is keep the arguments matching with each other. Have the ones in the calling command show the same names as the arguments in the function command. This way there may be less confusion dealing with two variable names doing the one job. <?phpfunction print_it_out($first_part,$second_part,$third_part){    echo "$first_part $second_part $third_part";}

$third_part = "HTMlite site.";$first_part = "Welcome";$second_part = "to the";

print_it_out($first_part,$second_part,$third_part);?>

Sometimes you may want to call a function and have a value returned back to the main coding area. This is done using the return command.

Page 38: Php

Example : <?phpfunction addit($first_number,$second_number){    $total_sum = $first_number + $second_number;    return $total_sum;}

$first_number = "1";$second_number ="2";$total = addit($first_number,$second_number);echo "$total";?>

Result : 3

Leaving the return command out, the result would be blank.

In the above example, the variable $total calls the function entering two arguments. The function takes the numbers and finds the sum. The sum value is "returned" back to the calling variable $total.

The include command is very similar to using an SSI include. It calls a block of information from a different page into the current webpage.

include ("filename.php");

Include will pass the information from an external page into the current one. The information that is passed will be known and usable to the coding that appears after the include command. Coding that appears before the include command will not "know" about the information contained in the included file.

info.php<?php$color = "yellow";$fruit = "bananas.";?>

test.php<?phpecho "I like $color $fruit <br>";include ("info.php");

Page 39: Php

echo "I like $color $fruit <br>";?>

Results : I likeI like yellow bananas.

One of the many uses of includes is to set common webpage areas into seperate files and include them into each page like a template style layout. This site uses php includes. One for the main header area, one for the navigations, and one for the footer area.

Another benefit to using includes would be to include a specific file IF a condition is true ELSE a different one upon a false condition.

The date and gmdate commands return the value of the current date. The regular date returns information based on the online host server. The gmdate returns information based on the Greenwich Meridian (the center of the timezones).

date ("formatting");gmdate ("formatting");

There are many variations to use in formatting the outcome of a date. Using the date command without any formatting will result as blank. Here is a list of formatting options :

a am or pmA AM or PMd day of the month - 01 to 31D day of the week - 3 lettersF month - long formatg hour of the day - 1 to 12G hour of the day - 0 to 23h hour of the day - 01 to 12H hour of the day - 00 to 23i minutes - 00 to 59j day of the month - 1 to 31l day of the week - long formatL leap year test - 0 or 1m month - 01 to 12M month - 3 lettersn month - 1 to 12s seconds - 00 to 59S English suffix - 2 letterst number of month days - 28 to 31

Page 40: Php

T timezone setting for this machineU seconds since epochw day of week - 0 to 6y year - 2 digitsY year - 4 digitsz day of the year - 0 to 365Z timezone offset in seconds

Using a combination of these letters, the date and time may be displayed in a number of ways. Example... echo "Today is " . date("F jS, Y") . "<br>";echo "The time is " . date("g:i:s a");

The result is : Today is April 7th, 2011The time is 9:52:41 pm