0% found this document useful (0 votes)
4 views28 pages

CH-5

PHP is an HTML-embedded scripting language designed for web development, allowing for the creation of dynamic web pages. It utilizes a syntax similar to C, Java, and Perl, and includes features such as variables, echoing strings, and various operators. The document provides an overview of PHP syntax, variable naming conventions, string creation, and operators, along with examples to illustrate their usage.

Uploaded by

Legesse Samuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views28 pages

CH-5

PHP is an HTML-embedded scripting language designed for web development, allowing for the creation of dynamic web pages. It utilizes a syntax similar to C, Java, and Perl, and includes features such as variables, echoing strings, and various operators. The document provides an overview of PHP syntax, variable naming conventions, string creation, and operators, along with examples to illustrate their usage.

Uploaded by

Legesse Samuel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

CHAPTER 5

HYPER TEXT PRE-PROCESSOR (PHP)

What is PHP?

PHP is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with
a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to
write dynamically generated pages quickly.

When someone visits your PHP webpage, your web server processes the PHP code. It then sees which
parts it needs to show to visitors (content and pictures) and hides the other stuff (file operations, math
calculations, etc.) then translates your PHP into HTML. After the translation into HTML, it sends the
webpage to your visitor's web browser.

PHP – What does it do?

It is also helpful to think of PHP in terms of what it can do for you. PHP will allow you to:

 Reduce the time to create large websites.


 Create a customized user experience for visitors based on information that you have gathered from
them.
 Open up thousands of possibilities for online tools. Check out PHP - HotScripts for examples of the
great things that are possible with PHP.
 Allow creation of shopping carts for e-commerce websites.

Syntax
PHP's syntax and semantics are similar to most other programming languages (C, Java, Perl) with the
addition that all PHP code is contained with a tag, of sorts. All PHP code must be contained within the
following...

PHP Code:
<?php

Code to be executed
?>

If you are writing PHP scripts and plan on distributing them, we suggest that you use the standard form
(which includes the ?php) rather than the shorthand form. This will ensure that your scripts will work, even
when running on other servers with different settings.

1|Page Internet and Web Development


How to Save Your PHP Pages

If you have PHP inserted into your HTML and want the web browser to interpret it correctly, then you
must save the file with a .php extension, instead of the standard .html extension. So be sure to check that
you are saving your files correctly. Instead of index.html, it should be index.php if there is PHP code in the
file.

Example

Below is an example of one of the easiest PHP and HTML page that you can create and still follow web
standards.

PHP and HTML Code:

<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>

Display:
Hello World!

If you save this file (e.g. helloworld.php) and place it on PHP enabled server and load it up in your web
browser, then you should see "Hello World!" displayed. If not, please check that you followed our example
correctly.

We used the PHP command echo to write "Hello World!" and we will be talking in greater depth about
how echo is special later on in this tutorial.

The Semicolon!

As you may or may not have noticed in the above example, there was a semicolon after the line of PHP
code. The semicolon signifies the end of a PHP statement and should never be forgotten. For example, if
we repeated our "Hello World!" code several times, then we would need to place a semicolon at the end of
each statement.

2|Page Internet and Web Development


White Space

As with HTML, whitespace is ignored between PHP statements. This means it is OK to have one line of
PHP code, then 20 lines of blank space before the next line of PHP code. You can also press tab to indent
your code and the PHP interpreter will ignore those spaces as well.

PHP and HTML Code:

<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<?php
echo "Hello World!";

echo "Hello World!";

?>
</body>
</html>

Display:
Hello World!Hello World!

PHP - Variables

A variable is a means of storing a value, such as text string "Hello World!" or the integer value . A variable
can then be reused throughout your code, instead of having to type out the actual value over and over again.
In PHP you define a variable with the following form:

 $variable_name = Value;

If you forget that dollar sign at the beginning, it will not work. This is a common mistake for new PHP
programmers!

Note: Also, variable names are case-sensitive, so use the exact same capitalization when using a variable.
The variables $a_number and $A_number are different variables in PHP's eyes.

3|Page Internet and Web Development


PHP Code:

<?php
$hello = "Hello World!";
$a_number = 4;
$anotherNumber = 8;
?>

Note for programmers: PHP does not require variables to be declared before being initialized.

PHP Variable Naming Conventions


There are a few rules that you need to follow when choosing a name for your PHP variables.

 PHP variables must start with a letter or underscore "_".


 PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _
 Variables with more than one word should be separated with underscores. $my_variable
 Variables with more than one word can also be distinguished with capitalization. $myVariable

Outputting a String
The PHP function echo is a means of outputting text to the web browser. Throughout your PHP career you will be
using the echo function more than any other. So let's give it a solid perusal! To output a string, like we have done
in previous lessons, use PHP echo. You can place either a string variable or you can use quotes, like we do
below, to create a string that the echo function will output.

PHP Code:
<?php
$myString = "Hello!";
echo $myString;
echo "<h5>I love using PHP!</h5>";
?>

Display:
Hello!

I love using PHP!

In the above example we output "Hello!" without a hitch. The text we are outputting is being sent to the
user in the form of a web page, so it is important that we use proper HTML syntax!

In our second echo statement we use echo to write a valid Header 5 HTML statement. To do this we simply
put the <h5> at the beginning of the string and closed it at the end of the string. Just because you're using
PHP to make web pages does not mean you can forget about HTML syntax!
4|Page Internet and Web Development
Careful When Echoing Quotes!

It is pretty cool that you can output HTML with PHP. However, you must be careful when using HTML
code or any other string that includes quotes! Echo uses quotes to define the beginning and end of the
string, so you must use one of the following tactics if your string contains quotations:

 Don't use quotes inside your string


 Escape your quotes that are within the string with a backslash. To escape a quote just place a
backslash directly before the quotation mark, i.e. \"
 Use single quotes (apostrophes) for quotes inside your string.

See our example below for the right and wrong use of echo:

PHP Code:

<?php
// This won't work because of the quotes around specialH5!
echo "<h5 class="specialH5">I love using PHP!</h5>";

// OK because we escaped the quotes!


echo "<h5 class=\"specialH5\">I love using PHP!</h5>";

// OK because we used an apostrophe’


echo "<h5 class='specialH5'>I love using PHP!</h5>";
?>

If you want to output a string that includes quotations, either use an apostrophe ( ' ) or escape the
quotations by placing a backslash in front of it ( \" ). The backslash will tell PHP that you want the
quotation to be used within the string and NOT to be used to end echo's string.

Echoing Variables
Echoing variables is very easy. The PHP developers put in some extra work to make the common task of
echoing all variables nearly foolproof! No quotations are required, even if the variable does not hold a
string. Below is the correct format for echoing a variable.

5|Page Internet and Web Development


PHP Code:

<?php
$my_string = "Hello Bob. My name is: ";
$my_number = 4;
$my_letter = “NANA &Bab”;
echo $my_string;
echo $my_number;
echo $my_letter;
?>

Display:

Hello Bob. My name is: 4NANA &Bab

Echoing Variables and Text Strings


You can also place variables inside of double-quoted strings (e.g. "string here and a $variable"). By putting
a variable inside the quotes (" ") you are telling PHP that you want it to grab the string value of that
variable and use it in the string. The example below shows an example of this cool feature.

PHP Code:
<?php
$my_string = "Hello Bob. My name is: ";
echo "$my_string Bobettta <br />";
echo "Hi, I'm Bob. Who are you? $my_string <br />";
echo "Hi, I'm Bob. Who are you? $my_string Bobetta";
?>

Display:
Hello Bob. My name is: Bobetta
Hi, I'm Bob. Who are you? Hello Bob. My name is:
Hi, I'm Bob. Who are you? Hello Bob. My name is: Bobetta

By placing variables inside a string you can save yourself some time and make your code easier to read,
though it does take some getting used to. Remember to use double-quotes, single-quotes will not grab the
value of the string. Single-quotes will just output the variable name to the string, like )$my_string), rather
than (Hello Bob. My name is: ).

Echo is not a function, rather it is a language construct. When you use functions in PHP, they have a very
particular form.

6|Page Internet and Web Development


PHP - String Creation

Before you can use a string you have to create it! A string can be used directly in a function or it can be
stored in a variable. Below we create the exact same string twice: first storing it into a variable and in the
second case we send the string directly to echo.

PHP Code:
<?php
$my_string = "israni - Unlock your potential!";
echo "israni - Unlock your potential!";
echo $my_string;
?>

In the above example the first string will be stored into the variable $my_string, while the second string
will be used in the echo and not be stored. Remember to save your strings into variables if you plan on
using them more than once! Below is the output from our example code. They look identical just as we
thought.

Display:
israni - Unlock your potential! israni - Unlock your potential!

PHP - String Creation Single Quotes


Thus far we have created strings using double-quotes, but it is just as correct to create a string using single-
quotes, otherwise known as apostrophes.

PHP Code:
$my_string = 'israni - Unlock your potential!';
echo 'israni - Unlock your potential!';
echo $my_string;

If you want to use a single-quote within the string you have to escape the single-quote with a backslash \ .
Like this: \' !

PHP Code:
echo 'israni - It\'s Neat!';

PHP - String Creation Double-Quotes

We have used double-quotes and will continue to use them as the primary method for forming strings.
Double-quotes allow for many special escaped characters to be used that you cannot do with a single-quote
string. Once again, a backslash is used to escape a character.

7|Page Internet and Web Development


PHP Code:
<?php
$newline = "A newline is \n";
$return = "A carriage return is \r";
$tab = "A tab is \t";
$dollar = "A dollar sign is \$";
$doublequote = "A double-quote is \"";
?>

Note: If you try to escape a character that doesn't need to be, such as an apostrophe, then the backslash will
show up when you output the string.

These escaped characters are not very useful for outputting to a web page because HTML ignore extra
white space. A tab, newline, and carriage return are all examples of extra (ignorable) white space.
However, when writing to a file that may be read by human eyes these escaped characters are a valuable
tool!

PHP - Operators

There are many operators used in PHP, so we have separated them into the following categories to make it
easier to learn them all.

 Assignment Operators
 Arithmetic Operators
 Comparison Operators
 String Operators
 Combination Arithmetic & Assignment Operators

Assignment Operators

Assignment operators are used to set a variable equal to a value or set a variable to another variable's value.
Such an assignment of value is done with the "=", or equal character. Example:

 $my_var = 4;
 $another_var = $my_var;

Now both $my_var and $another_var contain the value 4. Assignments can also be used in conjunction
with arithmetic operators.

8|Page Internet and Web Development


Arithmetic Operators

Operator English Example

+ Addition 2+4

- Subtraction 6-2

* Multiplication 5*3

/ Division 15 / 3

% Modulus 43 % 10

PHP Code:
<?php
$addition = 2 + 4;
$subtraction = 6 - 2;
$multiplication = 5 * 3;
$division = 15 / 3;
$modulus = 5 % 2;
echo "Perform addition: 2 + 4 = ".$addition."<br />";
echo "Perform subtraction: 6 - 2 = ".$subtraction."<br />";
echo "Perform multiplication: 5 * 3 = ".$multiplication."<br />";
echo "Perform division: 15 / 3 = ".$division."<br />";
echo "Perform modulus: 5 % 2 = " . $modulus
. ". Modulus is the remainder after the division operation has been performed.
In this case it was 5 / 2, which has a remainder of 1.";
?>

Display:
Perform addition: 2 + 4 = 6
Perform subtraction: 6 - 2 = 4
Perform multiplication: 5 * 3 = 15
Perform division: 15 / 3 = 5
Perform modulus: 5 % 2 = 1. Modulus is the remainder after the division operation has been performed. In this case
it was 5 / 2, which has a remainder of 1.

9|Page Internet and Web Development


Comparison Operators

Comparisons are used to check the relationship between variables and/or values. Comparison operators are
used inside conditional statements and evaluate to either true or false. Here are the most important
comparison operators of PHP.
Assume: $x = 4 and $y = 5;

Operator English Example Result

== Equal To $x == $y false

!= Not Equal To $x != $y true

< Less Than $x < $y true

> Greater Than $x > $y false

<= Less Than or Equal To $x <= $y true

>= Greater Than or Equal To $x >= $y false

String Operators
As we have already seen in the Echo Lesson, the period "." is used to add two strings together, or more
technically, the period is the concatenation operator for strings.

PHP Code:
<?php
$a_string = "Hello";
$another_string = " Billy";
$new_string = $a_string . $another_string;
echo $new_string . "!";
?>

Display:
Hello Billy!

Combination Arithmetic & Assignment Operators


In programming it is a very common task to have to increment a variable by some fixed amount. The most
common example of this is a counter. Say you want to increment a counter by 1, you would have:

 $counter = $counter + 1;

10 | P a g e Internet and Web Development


However, there is a shorthand for doing this.

 $counter += 1;

This combination assignment/arithmetic operator would accomplish the same task. The downside to this
combination operator is that it reduces code readability to those programmers who are not used to such an
operator. Here are some examples of other common shorthand operators. In general, "+=" and "-=" are the
most widely used combination operators.

Operator English Example Equivalent Operation

+= Plus Equals $x += 2; $x = $x + 2;

-= Minus Equals $x -= 4; $x = $x - 4;

*= Multiply Equals $x *= 3; $x = $x * 3;

/= Divide Equals $x /= 2; $x = $x / 2;

%= Modulo Equals $x %= 5; $x = $x % 5;

.= Concatenate Equals $my_str.="hello"; $my_str = $my_str . "hello";

Pre/Post-Increment & Pre/Post-Decrement

This may seem a bit absurd, but there is even a shorter shorthand for the common task of adding 1 or
subtracting 1 from a variable. To add one to a variable or "increment" use the "++" operator:

 $x++; Which is equivalent to $x += 1; or $x = $x + 1;

To subtract 1 from a variable, or "decrement" use the "--" operator:

 $x--; Which is equivalent to $x -= 1; or $x = $x - 1;

In addition to this "shorter hand" technique, you can specify whether you want to increment before the line
of code is being executed or after the line has executed. Our PHP code below will display the difference.
PHP Code:
<?php
$x = 4;
echo "The value of x with post-plusplus = " . $x++;
echo "<br /> The value of x after the post-plusplus is " . $x;
$x = 4;
echo "<br />The value of x with with pre-plusplus = " . ++$x;
echo "<br /> The value of x after the pre-plusplus is " . $x;
?>

11 | P a g e Internet and Web Development


Display:
The value of x with post-plusplus = 4
The value of x after the post-plusplus is = 5
The value of x with with pre-plusplus = 5
The value of x after the pre-plusplus is = 5

As you can see the value of $x++ is not reflected in the echoed text because the variable is not incremented
until after the line of code is executed. However, with the pre-increment "++$x" the variable does reflect
the addition immediately.

Using Comments in PHP

Comments in PHP are similar to comments that are used in HTML. The PHP comment syntax always
begins with a special character sequence and all text that appears between the start of the comment and the
end will be ignored.

In HTML a comment's main purpose is to serve as a note to you, the web developer or to others who may
view your website's source code. However, PHP's comments are different in that they will not be displayed
to your visitors. The only way to view PHP comments is to open the PHP file for editing. This makes PHP
comments only useful to PHP programmers.

In case you forgot what an HTML comment looked like, see our example below.

HTML Code:
<!-- This is an HTML Comment -->

PHP Comment Syntax: Single Line Comment

While there is only one type of comment in HTML, PHP has two types. The first type we will discuss is
the single line comment. The single line comment tells the interpreter to ignore everything that occurs on
that line to the right of the comment. To do a single line comment type "//" or "#" and all text to the right
will be ignored by PHP interpreter.

PHP Code:
<?php
echo "Hello World!"; // This will print out Hello World!
echo "<br />Psst...You can't see my PHP comments!"; // echo "nothing";
// echo "My name is Humperdinkle!";
# echo "I don't do anything either";
?>

Display:
Hello World!
Psst...You can't see my PHP comments!

12 | P a g e Internet and Web Development


Notice that a couple of our echo statements were not evaluated because we commented them out with the
single line comment. This type of line commenting is often used for quick notes about complex and
confusing code or to temporarily remove a line of PHP code.

PHP Comment Syntax: Multiple Line Comment


Similar to the HTML comment, the multi-line PHP comment can be used to comment out large blocks of
code or writing multiple line comments. The multiple line PHP comment begins with " /* " and ends with "
*/ ".

PHP Code:
<?php
/* This Echo statement will print out my message to the
the place in which I reside on. In other words, the World. */
echo "Hello World!";
/* echo "My name is Humperdinkle!";
echo "No way! My name is Uber PHP Programmer!";
*/
?>

Display:
Hello World!

Conditional statements

The If Statement
The PHP if statement is very similar to other programming languages use of the if statement, but for those
who are not familiar with it, picture the following:

Think about the decisions you make before you go to sleep. If you have something to do the next day, say
go to work, school, or an appointment, then you will set your alarm clock to wake you up. Otherwise, you
will sleep in as long as you like!

This simple kind of if/then statement is very common in every day life and also appears in programming
quite often. Whenever you want to make a decision given that something is true (you have something to do
tomorrow) and be sure that you take the appropriate action, you are using an if/then relationship.

The PHP If Statement

The if statement is necessary for most programming, thus it is important in PHP. Imagine that on January
1st you want to print out "Happy New Year!" at the top of your personal web page. With the use of PHP if
statements you could have this process automated, months in advance, occuring every year on January 1st.

13 | P a g e Internet and Web Development


This idea of planning for future events is something you would never have had the opportunity of doing if
you had just stuck with HTML.

Example

The "Happy New Year" example would be a little difficult for you to do right now, so let us instead start
off with the basics of the if statement. The PHP if statement tests to see if a value is true, and if it is a
segment of code will be executed. See the example below for the form of a PHP if statement.

PHP Code:
$my_name = "Eyerus";

if ( $my_name == "Eyerus" ) {
echo "Your name is Eyerus!<br />";
}
echo "Welcome to my homepage!";

Display:
Your name is Eyerus!
Welcome to my homepage!

Did you get that we were comparing the variable $my_name with "Eyerus" to see if they were equal? In
PHP you use the double equal sign (==) to compare values. Additionally, notice that because the if
statement turned out to be true, the code segment was executed, printing out "Your name is Eyerus!". Let's
go a bit more in-depth into this example to iron out the details.

 We first set the variable $my_name equal to " Eyerus ".


 We next used a PHP if statement to check if the value contained in the variable $my_name was equal to "
Eyerus "
 The comparison between $my_name and " Eyerus " was done with a double equal sign "==", not a single
equals"="! A single equals is for assigning a value to a variable, while a double equals is for checking if
things are equal.
 Translated into english the PHP statement ( $my_name == " Eyerus " ) is ( $my_name is equal to " Eyerus "
).
 $my_name is indeed equal to " Eyerus " so the echo statement is executed.

A False If Statement

Let us now see what happens when a PHP if statement is not true, in other words, false. Say that we
changed the above example to:

PHP Code:
$my_name = "anotherguy";

if ( $my_name == "someguy" ) {
echo "Your name is someguy!<br />";
}

14 | P a g e Internet and Web Development


echo "Welcome to my homepage!";

Display:
Welcome to my homepage!

Here the variable contained the value "anotherguy", which is not equal to "someguy". The if statement
evaluated to false, so the code segment of the if statement was not executed. When used properly, the if
statement is a powerful tool to have in your programming arsenal!

PHP - Elseif what is it?

An if statement is made up of the keyword "if" and a conditional statement (i.e. $name == "Ted"). Just like
an if statement, an elseif statement also contains a conditional statement, but it must be preceded by an if
statement. You cannot have an elseif statement without first having an if statement.

When PHP evaluates your If...elseif...else statement it will first see if the If statement is true. If that tests
comes out false it will then check the first elseif statement. If that is false it will either check the next elseif
statement, or if there are no more elseif statements, it will evaluate the else segment, if one exists (I don't
think I've ever used the word "if" so much in my entire life!). Let's take a look at a real world example.

PHP - Using Elseif with If...Else

Let's start out with the base case. Imagine we have a simpler version of the problem described above. We
simply want to find out if the employee is the Vice President Ms. Tanner. We only need an if else statement
for this part of the example.

PHP Code:
$employee = "Bob";
if($employee == "Ms. Tanner"){
echo "Hello Ma'am";
} else {
echo "Morning";
}
Now, if we wanted to also check to see if the big boss Bob was the employee we need to insert an elseif
clause.

PHP Code:
$employee = "Bob";
if($employee == "Ms. Tanner"){
echo "Hello Ma'am";
} elseif($employee == "Bob"){
echo "Good Morning Sir!";
}else {
echo "Morning";
}
?>

15 | P a g e Internet and Web Development


Display:
Good Morning Sir!

PHP first checked to see if $employee was equal to "Ms. Tanner", which evaluated to false. Next, PHP
checked the first elseif statement. $employee did in fact equal "Bob" so the phrase "Good Morning Sir!"
was printed out. If we wanted to check for more employee names we could insert more elseif statements!

Remember that an elseif statement cannot be used unless it is preceded by an if statement!

PHP Switch Statement: Speedy Checking


With the use of the switch statement you can check for all these conditions at once, and the great thing is
that it is actually more efficient programming to do this. A true win-win situation!

The way the Switch statement works is it takes a single variable as input and then checks it against all the
different cases you set up for that switch statement. Instead of having to check that variable one at a time,
as it goes through a bunch of If Statements, the Switch statement only has to check one time.

Example
In our example the single variable will be $destination and the cases will be: Las Vegas, Amsterdam,
Egypt, Tokyo, and the Caribbean Islands.

PHP Code:
$destination = "Tokyo";
echo "Traveling to $destination<br />";
switch ($destination){
case "Las Vegas":
echo "Bring an extra $500";
break;
case "Amsterdam":
echo "Bring an open mind";
break;
case "Egypt":
echo "Bring 15 bottles of SPF 50 Sunscreen";
break;
case "Tokyo":
echo "Bring lots of money";
break;
case "Caribbean Islands":
echo "Bring a swimsuit";
break;
}

16 | P a g e Internet and Web Development


Display:
Traveling to Tokyo
Bring lots of money

The value of $destination was Tokyo, so when PHP performed the switch operating on $destination in
immediately did a search for a case with the value of "Tokyo". It found it and proceeded to execute the
code that existed within that segment.

You might have noticed how each case contains a break; at the end of its code area. This break prevents
the other cases from being executed. If the above example did not have any break statements then all the
cases that follow Tokyo would have been executed as well. Use this knowledge to enhance the power of
your switch statements!

The form of the switch statement is rather unique, so spend some time reviewing it before moving on.
Note: Beginning programmers should always include the break; to avoid any unnecessary confusion.

PHP Switch Statement: Default Case

You may have noticed the lack of a place for code when the variable doesn't match our condition. The if
statement has the else clause and the switch statement has the default case.

It's usually a good idea to always include the default case in all your switch statements. Below is a
variation of our example that will result in none of the cases being used causing our switch statement to fall
back and use the default case. Note: the word case does not appear before the word default, as default is a
special keyword!

PHP Code:
$destination = "New York";
echo "Traveling to $destination<br />";
switch ($destination){
case "Las Vegas":
echo "Bring an extra $500";
break;
case "Amsterdam":
echo "Bring an open mind";
break;
case "Egypt":
echo "Bring 15 bottles of SPF 50 Sunscreen";
break;
case "Tokyo":
echo "Bring lots of money";
break;
case "Caribbean Islands":
echo "Bring a swimsuit";
break;
default:

17 | P a g e Internet and Web Development


echo "Bring lots of underwear!";
break;
}

Display:
Traveling to New York
Bring lots of underwear!

PHP - For Loop


The common tasks that are covered by a for loop are:

1. Set a counter variable to some initial value.


2. Check to see if the conditional statement is true.
3. Execute the code within the loop.
4. Increment a counter at the end of each iteration through the loop.

The for loop allows you to define these steps in one easy line of code. It may seem to have a strange form,
so pay close attention to the syntax used!. The basic structure of the for loop is as follows:

Pseudo PHP Code:


for ( initialize a counter; conditional statement; increment a counter){
do this code;
}

Notice how all the steps of the loop are taken care of in the for loop statement. Each step is separated by a
semicolon: initiliaze counter, conditional statement, and the counter increment. A semicolon is needed
because these are separate expressions. However, notice that a semicolon is not needed after the "increment
counter" expression.

Here is the example of the brush prices done with a for loop .

PHP Code:
$brush_price = 5;

echo "<table border=\"1\" align=\"center\">";


echo "<tr><th>Quantity</th>";
echo "<th>Price</th></tr>";
for ( $counter = 10; $counter <= 100; $counter += 10) {
echo "<tr><td>";
echo $counter;
echo "</td><td>";
echo $brush_price * $counter;
echo "</td></tr>";
}
echo "</table>";

18 | P a g e Internet and Web Development


Display:
Quantity Price

10 50

20 100

30 150

40 200

50 250

60 300

70 350

80 400

90 450

100 500

It is important to note that both the for loop and while loop implementation of the price chart table are both
OK at getting the job done. However, the for loop is somewhat more compact and would be preferable in
this situation. In later lessons we will see where the while loop should be used instead of the for loop.

PHP - Do While Loop


A "do while" loop is a slightly modified version of the while loop. If you recal from one of the previous
lessons on While Loops the conditional statement is checked comes back true then the code within the
while loop is executed. If the conditional statement is false then the code within the loop is not executed.

On the other hand, a do-while loop always executes its block of code at least once. This is because the
conditional statement is not checked until after the contained code has been executed.

19 | P a g e Internet and Web Development


PHP - While Loop and Do While Loop Contrast

A simple example that illustrates the difference between these two loop types is a conditional statement
that is always false. First the while loop:

PHP Code:
$Banana = 0;
while($Banana > 1){
echo "Dad...I like Banana! *Mam*";
}

Display:

As you can see, this while loop's conditional statement failed (0 is not greater than 1), which means the
code within the while loop was not executed. Now, can you guess what will happen with a do-while loop?

PHP Code:
$Banana = 0;
do {
echo "Dad...I like Banana! *Mam*";
} while ($Banana > 1);

Display:
Dad...I like Banana! *Mam*

The code segment " Dad...I like Banana!" was executed even though the conditional statement was false.
This is because a do-while loop first do's and secondly checks the while condition!

Chances are you will not need to use a do while loop in most of your PHP programming, but it is good to know it's
there!

PHP - Functions
A function is just a name we give to a block of code that can be executed whenever we need it.

For example, you might have a company motto that you have to display at least once on every webpage. If
you don't, then you get fired! Well, being the savvy PHP programmer you are, you think to yourself, "this
sounds like a situation where I might need functions."

Tip: Although functions are often thought of as an advanced topic for beginning programmers to learn, if
you take it slow and stick with it, functions can be just minor speedbump in your programming career. So
don't give up if functions confuse you at first!

20 | P a g e Internet and Web Development


Creating Your First PHP Function

When you create a function, you first need to give it a name, like myCompanyMotto. It's with this function
name that you will be able to call upon your function, so make it easy to type and understand.

The actual syntax for creating a function is pretty self-explanatory, but you can be the judge of that. First,
you must tell PHP that you want to create a function. You do this by typing the keyword function followed
by your function name and some other stuff (which we'll talk about later).

Here is how you would make a function called myCompanyMotto. Note: We still have to fill in the code for
myCompanyMotto.

PHP Code:
<?php
function myCompanyMotto(){
}
?>

Note: Your function name can start with a letter or underscore "_", but not a number!

With a properly formatted function in place, we can now fill in the code that we want our function to
execute. Do you see the curly braces in the above example "{ }"? These braces define where our function's
code goes. The opening curly brace "{" tells php that the function's code is starting and a closing curly
brace "}" tells PHP that our function is done!

We want our function to print out the company motto each time it's called, so that sounds like it's a job for
the echo command!

PHP Code:
<?php
function myCompanyMotto(){
echo "We deliver quantity, not quality!<br />";
}
?>

That's it! You have written your first PHP function from scratch! Notice that the code that appears within a
function is just the same as any other PHP code.

Using Your PHP Function

Now that you have completed coding your PHP function, it's time to put it through a test run. Below is a
simple PHP script. Let's do two things: add the function code to it and use the function twice.

21 | P a g e Internet and Web Development


PHP Code:
<?php
echo "Welcome to israni.com <br />";
echo "Well, thanks for stopping by! <br />";
echo "and remember... <br />";
?>

PHP Code with Function:


<?php
function myCompanyMotto(){
echo "We deliver quantity, not quality!<br />";
}
echo "Welcome to israni.com <br />";
myCompanyMotto();
echo "Well, thanks for stopping by! <br />";
echo "and remember... <br />";
myCompanyMotto();
?>

Display:
Welcome to israni.com
We deliver quantity, not quality!
Well, thanks for stopping by!
and remember...
We deliver quantity, not quality!

Although this was a simple example, it's important to understand that there is a lot going on and there are a
lot of areas to make errors. When you are creating a function, follow these simple guidelines:

 Always start your function with the keyword function


 Remember that your function's code must be between the "{" and the "}"
 When you are using your function, be sure you spell the function name correctly
 Don't give up!

PHP Functions - Parameters


Another useful thing about functions is that you can send them information that the function can then use.
Our first function myCompanyMotto isn't all that useful because all it does, and ever will do, is print out a
single, unchanging string.

However, if we were to use parameters, then we would be able to add some extra functionality! A
parameter appears with the parentheses "( )" and looks just like a normal PHP variable. Let's create a new
function that creates a custom greeting based off of a person's name.

22 | P a g e Internet and Web Development


Our parameter will be the person's name and our function will concatenate this name onto a greeting string.
Here's what the code would look like.

PHP Code with Function:


<?php
function myGreeting($firstName){
echo "Hello there ". $firstName . "!<br />";
}
?>

When we use our myGreeting function we have to send it a string containing someone's name, otherwise it
will break. When you add parameters, you also add more responsibility to you, the programmer! Let's call
our new function a few times with some common first names.

PHP Code:
<?php
function myGreeting($firstName){
echo "Hello there ". $firstName . "!<br />";
}
myGreeting("Jack");
myGreeting("Ahmed");
myGreeting("Julie");
myGreeting("Charles");
?>

Display:
Hello there Jack!
Hello there Ahmed!
Hello there Julie!
Hello there Charles!

It is also possible to have multiple parameters in a function. To separate multiple parameters PHP uses a
comma ",". Let's modify our function to also include last names.

PHP Code:
<?php
function myGreeting($firstName, $lastName){
echo "Hello there ". $firstName ." ". $lastName ."!<br />";
}
myGreeting("Jack", "Black");
myGreeting("Ahmed", "Zewail");
myGreeting("Julie", "Roberts");
myGreeting("Charles", "Schwab");
?>

23 | P a g e Internet and Web Development


Display:
Hello there Jack Black!
Hello there Ahmed Zewail!
Hello there Julie Roberts!
Hello there Charles Schwab!

PHP Functions - Returning Values

Besides being able to pass functions information, you can also have them return a value. However, a
function can only return one thing, although that thing can be any integer, float, array, string, etc. that you
choose!

How does it return a value though? Well, when the function is used and finishes executing, it sort of
changes from being a function name into being a value. To capture this value you can set a variable equal
to the function. Something like:

 $myVar = somefunction();

Let's demonstrate this returning of a value by using a simple function that returns the sum of two integers.

PHP Code:
<?php
function mySum($numX, $numY){
$total = $numX + $numY;
return $total;
}
$myNumber = 0;
echo "Before the function, myNumber = ". $myNumber ."<br />";
$myNumber = mySum(3, 4); // Store the result of mySum in $myNumber
echo "After the function, myNumber = " . $myNumber ."<br />";
?>

Display:
Before the function, myNumber = 0
After the function, myNumber = 7

When we first print out the value of $myNumber it is still set to the original value of 0. However, when we
set $myNumber equal to the function mySum, $myNumber is set equal to mySum's result. In this case, the
result was 3 + 4 = 7, which was successfully stored into $myNumber and displayed in the second echo
statement!

24 | P a g e Internet and Web Development


Creating the HTML Form
If you need a refresher on how to properly make an HTML form, check out the HTML Form Lesson before
continuing on.

We first create an HTML form that will let our customer choose what they would like to purchase. This file
should be saved as "order.html"

order.html Code:
<html><body>
<h4>israni Art Supply Order Form</h4>
<form>
<select>
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input type="text" />
<input type="submit" />
</form>
</body></html>

Display:
israni Art Supply Order Form

Quantity:

Remember to review HTML Forms if you do not understand any of the above HTML code. Next we must
alter our HTML form to specify the PHP page we wish to send this information to. Also, we set the method
to "post".

order.html Code:
<html><body>
<h4>israni Art Supply Order Form</h4>
<form action="process.php" method="post">
<select name="item">
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
Quantity: <input name="quantity" type="text" />
<input type="submit" />

25 | P a g e Internet and Web Development


</form>
</body></html>

Now that our "order.html" is complete, let us continue on and create the "process.php" file which will
process the HTML form information.

PHP Form Processor

We want to get the "item" and "quantity" inputs that we have specified in our HTML form. The proper way
to get this information would be to create two new variables, $item and $quantity and set them equal to the
values that have been "posted". The name of this file is "process.php".

process.php Code:
<html><body>
<?php
$quantity = $_POST['quantity'];
$item = $_POST['item'];

echo "You ordered ". $quantity . " " . $item . ".<br />";
echo "Thank you for ordering from israni Art Supplies!";

?>
</body></html>

As you probably noticed, the name in $_POST['name'] corresponds to the name that we specified in our
HTML form.

Now try uploading the "order.html" and "process.php" files to a PHP enabled server and test them out. If
someone selected the item brushes and specified a quantity of 6, then the following would be displayed on
"process.php":

process.php Code:
You ordered 6 brushes.
Thank you for ordering from israni Art Supplies!

PHP & HTML Form Review

A lot of things were going on in this example. Let us step through it to be sure you understand what was
going on.

1. We first created an HTML form "order.html" that had two input fields specified, "item" and "quantity".
2. We added two attributes to the form tag to point to "process.php" and set the method to "post".
3. We had "process.php" get the information that was posted by setting new variables equal to the values in the
$_POST associative array.
4. We used the PHP echo function to output the customers order.

26 | P a g e Internet and Web Development


Remember, this lesson is only to teach you how to use PHP to get information from HTML forms. The
example on this page should not be used for a real business.

PHP - POST & GET

POST - Review

In our PHP Forms Lesson we used the post method. This is what the pertinent line of HTML code looked
like:

HTML Code Excerpt:


<form action="process.php" method="post">
<select name="item">
...
<input name="quantity" type="text" />

This HTML code specifies that the form data will be submitted to the "process.php" web page using the
POST method. The way that PHP does this is to store all the "posted" values into an associative array
called "$_POST". Be sure to take notice the names of the form data names, as they represent the keys in the
"$_POST" associative array.

Now that you know about associative arrays, the PHP code from "process.php" should make a litte more
sense.

PHP Code Excerpt:


$quantity = $_POST['quantity'];
$item = $_POST['item'];

The form names are used as the keys in the associative array, so be sure that you never have two input
items in your HTML form that have the same name. If you do, then you might see some problems arise.

PHP - GET

As we mentioned before, the alternative to the post method is get. If we were to change our HTML form to
the get method, it would look like this:

HTML Code Excerpt:


<form action="process.php" method="get">
<select name="item">
...
<input name="quantity" type="text" />

The get method is different in that it passes the variables along to the "process.php" web page by appending
them onto the end of the URL. The URL, after clicking submit, would have this added on to the end of it:

27 | P a g e Internet and Web Development


"?item=##&quantity=##"

The question mark "?" tells the browser that the following items are variables. Now that we changed the
method of sending information on "order.html", we must change the "process.php" code to use the
"$_GET" associative array.

PHP Code Excerpt:


$quantity = $_GET['quantity'];
$item = $_GET['item'];

After changing the array name the script will function properly. Using the get method displays the variable
information to your visitor, so be sure you are not sending password information or other sensitive items
with the get method. You would not want your visitors seeing something they are not supposed to!

28 | P a g e Internet and Web Development

You might also like