Tutorial: Introduction To PHP Part I

Dr. Thomas E. Hicks
Computer Science Department
Trinity University


PHP

1] PHP is a middleware language that can be used with both the Apache Web Server and The Internet Information Server. This tutorial shall focus on PHP 4!

2] PHP pages have the extension .php

3] As a middleware scripting language, PHP co-exists with HTML scripting; it was designed for Web Programmers.

4] PHP has built-in support for a large collection of databases.

5] PHP is much faster than Perl and CGI alternatives.

6] PHP is open source. It is well maintained and portable.


Home Directory

1] The files for this lab shall be placed in directory C:\Inetpub\wwwroot\PHP  (See Below!)



C:\Inetpub\wwwroot\ home Directory For IIS Web Server

C:\Inetpub\wwwroot is the home directory for the IIS Web Server.  (See Below!)
 

C:\Inetpub\wwwroot\ home Directory For Apache Web Server

C:\Inetpub\wwwroot is the home directory for the Apache Web Server. Apache is configured to port 180. (See Below!)
 

Beginning & Ending A Block Of PHP 

1] Regular Tags <? PHP  ..........................  ?>

2] Short Tags <? ....................................... ?.  [Don't recommend since used for XML processing instructions!]

3]  <SCRIPT LANGUAGE = "php". ........ <SCRIPT>


Hello.php  - Echo- Print

1] Write the PHP to generate the Web Page Below without using any HTML coding outside the PHP Code Block.  (See Below!)
 

2] Both the Echo and the Print commands can be used to create dynamic HTML code.  (See Below!)

3] PHP Commands end with a semi-colon.

4] Double Quotes bound the string.

5] HTML Code scripting my be included within the string.

6] The PHP commands are not case sensitive.
 

<?PHP
Echo "<CENTER><H1>Hello.PHP Application</H1>";
print "<H2>Written By</H2>";
Print ("<H3>Dr. Thomas E. Hicks</H3>");
?>

7] Just like ASP code, the server strips all of the middleware scripting from the page and returns traditional HTML code. The screen capture below shows the source code from the web rendered by the server at the start of this section.  (See Below!)

8] Things output by the Print() function generally wind up in the browser window! Although data is generally placed to the function within the parentheses, it will work on some servers without them.


Comments

1] // Comment 1

2] # Comment 2

3] /* Comment 3
       Comment 4
       Comment 5 */


About Variables

1] Variable Names are preceded by a $

2] Assignment Statement ==> $Name = "Dr. Thomas Hicks;

3] Variables may contain Numbers [0-9], Letters[A-Z, a-z], Underscore [_]

4] Standard Data Types : Integer, Double, String, Boolean, Object, and Array

5] Special Data Types: NULL [Un-Initialized Variables] & Resource [Third Party Objects Such As Databases]

6] Dynamic Data Typing

$A  = 2;
$A = "tom";
$A = true;


Assignment Statement

1]  Integer Dynamic data-typing

    $Quantity = 5;

2]  Double Dynamic data-typing

    $PayPerHour = 15.75;

3]  String Dynamic data-typing

    $Name = "Tom";

4]  Boolean Dynamic data-typing

    $Valid = true;

5]  Array Dynamic data-typing

    $Stooges = array("Larry", "Curley", "Moe");


GetType( )
1] Function GetType returns the datatype  (See Below!)

<?PHP
$Quantity = 5;
$PayPerHour = 15.75;
$Name = "Tom";
$Valid = true;
$Stooges = array("Larry", "Curley", "Moe");

Print ("<BR> GetType($Quantity) = ");
Print (GetType($Quantity));
Print ("<BR> GetType($PayPerHour) = ");
Print (GetType($PayPerHour));
Print ("<BR> GetType($Name) = ");
Print (GetType($Name));
Print ("<BR> GetType($Valid) = ");
Print (GetType($Valid));
Print ("<BR> GetType($Stooges) = ");
Print (GetType($Stooges));
?>


2] The output from the code above may be seen below:
[Note that 5 is substituted for $Quantity even in the string]
 
GetType(5) = integer
GetType(15.75) = double
GetType(Tom) = string
GetType(1) = boolean
GetType(Array) = array

SetType ( )

1] Function SetType is used to change/cast the datatype  (See Below!)

<?PHP
$Quantity = "5";
Print ("<BR> $ Quantity = $Quantity");
Print ("<BR> GetType($ Quantity) = ");
Print (GetType($Quantity));
SetType ($Quantity, 'integer');
Print ("<BR> GetType($ Quantity) = ");
Print (GetType($Quantity));
$Quantity = $Quantity * 2;
Print ("<BR> $ Quantity = $Quantity");
?>

2] The output from the code above may be seen below:

$ Quantity = 5
GetType($ Quantity) = string
GetType($ Quantity) = integer
$ Quantity = 10

Mathematics & Assignment Operators

1] + Addition ==> X$ = 2 + 3;  // $X = 5

2] - Subtraction ==> X$ = 8 - 3;  // $X = 5

3] *  Multiplication ==> X$ = 2 * 3;  // $X = 6

4] + Division ==> X$ = 15 / 3;  // $X = 5

5] % Modulus ==> X$ = 11 % 3;  // $X = 2

6]  X$ = 2  += ==> X$ += 3;  // $X = 5

7]  X$ = 2  *= ==> X$ *= 3;  // $X = 6

8]  X$ = 2  -= ==> X$ -= 3;  // $X = -1

9]  X$ = 8  /= ==> X$ /= 2;  // $X = 4

10]  X$ = 7  %= ==> X$ %= 3;  // $X = 1


Comparison & Logical Operators

1]
 == Equivalence ==> if ($X == 5) ... true/false

2]  != Non-Equivalence ==> if ($X != 5) ... true/false

3]  > Greater Than ==> if ($X > 5) ... true/false

4]   < Less Than ==> if ($X < 5) ... true/false

5]   >= Greater Than Or Equal To ==> if ($X >= 5) ... true/false

6]   <= Less Than Or Equal To ==> if ($X <= 5) ... true/false

7]   ||    OR  ==> if ($X || $Y) ... true/false
     
or OR  ==> if ($X or $Y) ... true/false

8]   &&    AND ==> if ($X || $Y) ... true/false
      and  AND ==> if ($X and $Y) ... true/false

9]   !    NOT ==> if (! $X) ... true/false


Constants

1]
define ("PI", 3.14)
 

Conditional Statements #1

1 ] Write A Block Of PHP Code That Will Display “Eggen” In The Biggest & Boldest Font If $FacultyNo Is 1
 
<?PHP
$FacultyNo = 1;
if ($FacultyNo == 1)
{
    Print ("<H1>Eggen</H1>");
}
?>

Conditional Statements #2

1 ] Write A Block Of PHP Code That Will Display “Eggen” In The Biggest & Boldest Font If $FacultyNo Is 1; otherwise Display "Not Eggen"
 
<?PHP
$FacultyNo = 2;
If ($FacultyNo == 1)
   Print ("<H1>Eggen</H1>");
Else
   Print ("<H1>Not Eggen</H1>");
?>


2 ] Like C/C++, one need not include braces to bind a single statement.


Example

1]  What would be the output from the PHP code below?
 
<?PHP
$FacultyNo = 1;
If ($FacultyNo == 1)
   Print ("<H1>Eggen</H1>");
Else
   Print ("<H1>Not Eggen</H1>");
   Print ("<H1>Might Be Hicks!</H1>");
?>

2] Since there are no braces around the two print statements in the else clause, only the first is associated with the conditional statement.


Conditional Statement # 3

1] Write A Block Of PHP Code That Will Display “Eggen” In The Biggest & Boldest Font If $FacultyNo Is 1; Display “Hicks” if 2; Display “Pitts” if 3; Otherwise Display “Unknown!”!
 
<?PHP
$FacultyNo = 4;
if ($FacultyNo == 1)
   print ("<H1>Eggen</H1>");
elseif($FacultyNo == 2)
   print ("<H1>Hicks</H1>");
elseif($FacultyNo == 3)
   print ("<H1>Pitts</H1>");
else
   print ("<H1>UnKnown</H1>");
?>

Case Statement

1] Write A Block Of PHP Code That Will Display “Eggen” In The Biggest & Boldest Font If $FacultyNo Is 1; Display “Hicks” if 2; Display “Pitts” if 3; Otherwise Display “Unknown!”!

 
<?PHP
$FacultyNo = 2;
Switch ($FacultyNo)
{
   Case 1:
      Print ("<H1>Eggen</H1>");
      Break;
   Case 2:
      Print ("<H1>Hicks</H1>");
      Break;
   Case 3:
      Print ("<H1>Pitts</H1>");
      Break;
   Default:
       Print ("<H1>UnKnown</H1>");
}
?>

While - Pretest Loop

1] Write A Block Of PHP Code That Will Display 20 random numbers in the range 1-100, one to a line. Function rand( ) % 10 returns a random number in the range 0-9. Use a Pretest Loop!
 
<?PHP
$Pos = 1;
While ($Pos <= 20)
{
   $RandNo = rand() % 100 + 1;
   Print ($RandNo);
   Print ("<BR>");
   $Pos = $Pos + 1;
}
?>

2] Output shall be something similar to the following: [Specific numbers will vary unless you set the seed using srand( ).     (See Below!)


Repeat Until - Do While - Posttest Loop

1] Write A Block Of PHP Code That Will Display 20 random numbers in the range 1-100, one to a line. Function rand( ) % 10 returns a random number in the range 0-9. Use a Repeat Posttest Loop!
 
<?PHP
$Pos = 1;
Do
{
   $RandNo = rand() % 100 + 1;
   Print ($RandNo);
   Print ("<BR>");
   $Pos = $Pos + 1;
}
While ($Pos <= 20)
?>

2] Output shall be something similar to the following: [Specific numbers will vary unless you set the seed using srand( ).     (See Below!)


Fixed Repetition - For - Loop

1] Write A Block Of PHP Code That Will Display 20 random numbers in the range 1-100, one to a line. Function rand( ) % 10 returns a random number in the range 0-9. Use a Fixed Repetition Loop!
 
<?PHP
For ($Pos = 1; $Pos <= 20; $Pos ++)
{
   $RandNo = rand() % 100 + 1;
   Print ($RandNo);
   Print ("<BR>");
}
?>

2] Output shall be something similar to the following: [Specific numbers will vary unless you set the seed using srand( ).     (See Below!)


Procedure - Non-Explicit Functions With  No Arguments

1] Write the PHP code for a function, called BigGreetings( ) which will display "Greetings From Trinity University" centered in the biggest and boldest font.
 
Function BigGreetings()
{
   Print ("<H1><CENTER> Greetings From Trinity University </CENTER></H1>");
}

2] The function is called with the line

         BigGreetings( );


3] Putting it all together:   (See Below!)
 
<?PHP
Function BigGreetings()
{
Print ("<H1><CENTER> Greetings From Trinity University </CENTER></H1>");
}

BigGreetings();
?>
<HR><CENTER> Separator </CENTER><HR>

<?PHP
BigGreetings();
?>

4] I recommend placing all functions at the top of the page. They may be called where needed. (See Below!)


Procedure - Non-Explicit Functions With Arguments

1] Write the PHP code for a function, called Square( ) which will display the square of the passed numerical value centered in the biggest and boldest font one to a line. Assume that this is the the portion of the page which evokes/calls your Square function. Assume the following code to evoke/call your function.
 

<?PHP
For ($Pos = 5; $Pos >= 1; $Pos --)
{
   Square($Pos);
}
?>

2] The function is called with the line

         Square($Pos);

3] The Code For The Square function.

Function Square($No)
{
   Print ("<H1><CENTER>");
   Print ($No * $No);
   Print ("</CENTER></H1>");
}


4] Putting it all together:   (See Below!)
 

<?PHP
Function Square($No)
{
   Print ("<H1><CENTER>");
   Print ($No * $No);
   Print ("</CENTER></H1>");
}
?>

<?PHP
For ($Pos = 5; $Pos >= 1; $Pos --)
{
   Square($Pos);
}
?>

5] I recommend placing all functions at the top of the page. They may be called where needed. (See Below!)


Explicit Functions With Arguments

1] Write the PHP code for a function, called Sum ( ) which will explicitly return the sum of the two passed numerical arguments. Assume the following code to evoke/call your function.

<?PHP
For ($Pos = 1; $Pos <= 9; $Pos ++)
{
   Print ("<BR> 2 + ");
   Print ($Pos);
   Print (" = ");
   Print Sum(2, $Pos);
}
?>

2] The function is called with

         Sum(2, $Pos)

3] The Code For The Sum function.

Function Sum($No1, $No2)
{
   $ReturnValue = $No1 + $No2;
   return ($ReturnValue);
}


4] Putting it all together: (See Below!)  Variables declared within a function are local/available only within that function.
 

<?PHP
Function Sum($No1, $No2)
{
   $ReturnValue = $No1 + $No2;
   return ($ReturnValue);
}
?>

<?PHP
For ($Pos = 1; $Pos <= 9; $Pos ++)
{
   Print ("<BR> 2 + ");
   Print ($Pos);
   Print (" = ");
   Print Sum (2, $Pos);
}
?>

5] I recommend placing all functions at the top of the page. They may be called where needed. (See Below!)


Global &  Local Variables

1] Variable $ReturnValue is a local variable to the Sum function and is not available outside the function.

2]Variable $No1 is not local to any function. It is a Global, On Demand, Variable. Any function, that includes the global statement Global $No1; shall have access to the contents of $No1. (See Below!)

<?PHP
$No1 = 2;
Function Sum($No2)
{
Global $No1;

   $ReturnValue = $No1 + $No2;
   return ($ReturnValue);
}
?>

<?PHP
For ($Pos = 1; $Pos <= 9; $Pos ++)
{
   Print ("<BR> ");
   Print ($No1);
   Print (" + ");
   Print ($Pos);
   Print (" = ");
   Print Sum($Pos);
}
?>

3] Although the Sum function in the previous example is much better designed, the output from the code above will look much like the output from the previous example. (See Below!)


Create Arrays #1

1] Write the PHP code to create an array, called $Names and initialize it with Tom, Dick,  and Harry. Display the elements of the array elements one to a line.
 
<?PHP
$Names = Array ("Tom", "Dick", "Harry");

For ($Pos = 0; $Pos <= 2; $Pos ++)
{
   Print ($Names[$Pos]);
   Print ("<BR> ");
}
Print ("<P> No Elements In Array Names = ");
Print (Count($Names));
?>

2] The array subscripting begins with element 0. The Count function explicitly returns the number of elements in the array.

Tom
Dick
Harry
 

No Elements In Array Names = 3


Create Arrays #2

1] Write the Output from the following PHP code.
 
<?PHP
$Names[4] = "Ann";
$Names[2] = "Sally";
$Names[17] = "Judy";


ForEach ($Names As $Name)
{
   Print ($Name);
   Print ("<BR> ");
}
Print ("<P> No Elements In Array Names = ");
Print (Count($Names));
?>

2] As you can see, the array subscripts need not be sequential. When using the ForEach statement, they are rendered in exactly the same order in which they are filled.

Ann
Sally
Judy
 

No Elements In Array Names = 3


Create Array # 3

1] Write the Output from the following PHP code.

<?PHP
$Names[1] = "Ann";
$Names[2] = "Sally";
$Names[0] = "Judy";


For ($Pos = 0; $Pos <= 2; $Pos ++)
{
   Print ($Names[$Pos]);
   Print ("<BR> ");
}
Print ("<P> No Elements In Array Names = ");
Print (Count($Names));
?>

2] When consecutive subscripts are used, the for loop will output data in sequential order.

Judy
Ann
Sally
 

No Elements In Array Names = 3


Create Arrays # 4

1] Write the Output from the following PHP code.
 
<?PHP
$Names[0] = "Tom";
$Names[1] = "Hicks";
$Names[2] = "999-7483";
$Names[3] = "Male";
$Names[4] = 50;
$Names[5] = true;


For ($Pos = 0; $Pos <= 5; $Pos ++)
{
   Print ($Names[$Pos]);
   Print ("<BR> ");
}
Print ("<BR> No Elements In Array Names = ");
Print (Count($Names));
?>

2] Just as normal variables utilize dynamic data-typing, each element in the array also can accept dynamic data-typing.

Tom
Hicks
999-7483
Male
50
1

No Elements In Array Names = 6


Create Arrays # 5

1] Write the Output from the following PHP code.
 
<?PHP
$Names[] = "Tom";
$Names[] = "Dick";
$Names[] = "Harry";

ForEach ($Names As $Name)
{
   Print ($Name);
   Print ("<BR> ");
}
Print ("<P> No Elements In Array Names = ");
Print (Count($Names));
Print ("<P> ");

$Names[] = "Jennifer";
$Names[] = "Monica";
$Names[] = "Susan";

ForEach ($Names As $Name)
{
   Print ($Name);
   Print ("<BR> ");
}
Print ("<P> No Elements In Array Names = ");
Print (Count($Names));
?>

2] $Names[] = ????   appends a new value to the array!

Tom
Hicks
999-7483
Male
50
1

No Elements In Array Names = 6


Create Arrays # 6

1] Write the Output from the following PHP code.

<?PHP
$Users = Array( "First" => "Tom",
                "Last" => "Hicks",
                "Phone" => "999-7483",
                "Dept" => "CompSci");

Print "<BR> First : ";
Print $Users["First"];

Print "<BR> Last : ";
Print $Users["Last"];

Print "<BR> Phone : ";
Print $Users["Phone"];

Print "<BR> Dept : ";
Print $Users["Dept"];
?>

2] This sort of allows us to easily access a record within the array structure.

First : Tom
Last : Hicks
Phone : 999-7483
Dept : CompSci

3] What if we had several users? See the next section!


Multi-Dimensional Array # 7

1] Write the Output from the following PHP code.

<?PHP
$Users = Array (

                 Array ( "First" => "Tom",
                         "Last" => "Hicks",
                         "Phone" => "999-7483",
                         "Dept" => "CompSci"),

                 Array ( "First" => "Maurice",
                         "Last" => "Eggen",
                         "Phone" => "999-7487",
                         "Dept" => "CompSci"),

                 Array ( "First" => "Suzanne",
                         "Last" => "Williams",
                         "Phone" => "999-7543",
                         "Dept" => "Communications")
                );

ForEach ($Users as $User)
   ForEach ($User As $Key=>$Data) 
      Print ("$Key: $Data<BR>");
?>

2] It is amazing what one can do with just three lines of output at the bottom.

First: Tom
Last: Hicks
Phone: 999-7483
Dept: CompSci
First: Maurice
Last: Eggen
Phone: 999-7487
Dept: CompSci
First: Suzanne
Last: Williams
Phone: 999-7543
Dept: Communications


Array_Push

1] Write a block of code that demonstrates the built in Array_Push Utility.
<?PHP
$Stack = Array ("Tom", "Dick", "Harry");
$NoElements = Array_Push ($Stack, 1, 2);

For ($Pos = 0; $Pos < Count($Stack); $Pos ++)
   Print ("<BR> $Stack[$Pos]");
Print ("<P> There Are Now $NoElements in \$Stack");
?>

2] Not that push does not insert the info at the beginning of the array; at the end! Append! Array_Push explicitly returns the number of elements in the Array.

Tom
Dick
Harry
1
2

There Are Now 5 in $Stack


Array_Merge

1] Write a block of code that demonstrates the built in Array_Merge Utility.

<?PHP
$Array1 = Array ("Tom", "Dick", "Harry");
$Array2 = Array (1, 2, 3);
$Array3 = Array_Merge($Array1, $Array2);

For ($Pos = 0; $Pos < Count($Array3); $Pos ++)
Print ("<BR> $Array3[$Pos]");
?>

2] Easy!

Tom
Dick
Harry
1
2
3


Array_Shift

1] Write a block of code that demonstrates the built in Array_Shift Utility.
<?PHP
$Names = Array ("Tom", "Dick", "Harry", "Susan");

While (Count($Names) != 0)
{
   Print ("<BR> There Is/Are ".Count($Names)." Element(s) In The Array ==> ");
   ForEach ($Names As $Name)
      Print("$Name, ");
   $Element = Array_Shift($Names);
   Print ("<P> Removed Was : $Element <BR>");
}
?>

2] Function Array_Shift removes the first element of the array.

There Is/Are 4 Element(s) In The Array ==> Tom, Dick, Harry, Susan,

Removed Was : Tom

There Is/Are 3 Element(s) In The Array ==> Dick, Harry, Susan,

Removed Was : Dick

There Is/Are 2 Element(s) In The Array ==> Harry, Susan,

Removed Was : Harry

There Is/Are 1 Element(s) In The Array ==> Susan,

Removed Was : Susan


ASort

1] Write a block of code that demonstrates the built in ASort Utility.
 
<?PHP
$Names = Array ("Tom", "Dick", "Harry", "Susan", "Amy", "Paul", "Maury");

ForEach ($Names As $Name)
   Print("$Name, ");
ASort($Names);
Print ("<P> After Sort <P>");
ForEach ($Names As $Name)
   Print("$Name, ");
?>

2] Function Array_Shift removes the first element of the array.

Tom, Dick, Harry, Susan, Amy, Paul, Maury,

After Sort

Amy, Dick, Harry, Maury, Paul, Susan, Tom,


PHP

1] PHP is a middleware language that can be used with both the Apache Web Server and The Internet Information Server. This tutorial shall focus on PHP 4!

2] PHP pages have the extension .php

3] As a middleware scripting language, PHP co-exists with HTML scripting; it was designed for Web Programmers.

4] PHP has built-in support for a large collection of databases.

5] PHP is much faster than Perl and CGI alternatives.

6] PHP is open source. It is well maintained and portable.


Home Directory

1] The files for this lab shall be placed in directory
C:\Inetpub\wwwroot\PHP  (See Below!)
 

May be accessed through URL: http://www.cs.trinity.edu/~thicks
May also be accessed through URL: http://carme.cs.trinity.edu
This Document May Not Be Printed or Reproduced Without Written Permission.
 2003 Copyright : Dr. Thomas E. Hicks
Permission granted : Professional Educators & College Students may print one copy of this page!

Dr. Thomas E. Hicks

Computer Science Department    
Trinity University

"Dr. Web"