Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Php work book
Description: this php notes is for better understanding of students. this helps every one to gain knowledge on php. each and every topic explained with example so that learnig is made easy.

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


PHP Tutorial - Learn PHP
If you want to learn the basics of PHP, then you've come to the right place
...

Begin to understand the working model of PHP, so you may begin to design your own PHP projects
...


PHP stands for PHP Hypertext Preprocessor
...
net, "PHP is an HTML-embedded scripting language
...
The goal of
the language is to allow web developers to write dynamically generated pages quickly
...
However, it does contain a lot of terms you may not be used to
...
It then sees which
parts it needs to show to visitors(content and pictures) and hides the other stuff(file operations, math
calculations, etc
...
After the translation into HTML, it sends the webpage to
your visitor's web browser
...
PHP will allow you to:






Reduce the time to create large websites
...

Open up thousands of possibilities for online tools
...

Allow creation of shopping carts for e-commerce websites
...

Basic programming knowledge - This isn't required, but if you have any traditional programming
experience it will make learning PHP a great deal easier
...
If you want a drivethrough PHP tutorial this probably is not the right tutorial for you
...
Read a couple lessons, take a
break, then do some more after the information has had some time to sink in
...
tizag
...
php

PHP - Syntax
Before we talk about PHP's syntax, let us first define what syntax is referring to
...


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
...


PHP Code:
?>
or the shorthand PHP tag that requires shorthand support to be enabled
on your server
...
This will ensure that your scripts will work, even
when running on other servers with different settings
...
php extension, instead of the standard
...
So be sure to check that you are
saving your files correctly
...
html, it should be index
...


Example Simple HTML & PHP Page
Below is an example of one of the easiest PHP and HTML page that you can create and still follow web
standards
...
If not, please check that you followed our example correctly
...


The Semicolon!
As you may or may not have noticed in the above example, there was a semicolon after the line of PHP
code
...
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
...
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
...


PHP and HTML Code:


My First PHP Page


echo "Hello World!";
echo "Hello World!";
?>



Display:
Hello World!Hello World!
This is perfectly legal PHP code
...
A detailed explanation of variables is beyond the scope of this tutorial, but
we've included a refresher crash course to guide you
...
A
variable can then be reused throughout your code, instead of having to type out the actual value over and over
again
...
This is a common mistake for new PHP
programmers!

A Quick Variable Example
Say that we wanted to store the values that we talked about in the above paragraph
...

See our example below for the correct way to do this
...


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

PHP variables may only be comprised of alpha-numeric characters and underscores
...

Variables with more than one word should be separated with underscores
...
$myVariable

PHP - Echo
As you saw in the previous lesson, the PHP function echo is a means of outputting text to the web
browser
...
So let's give it a
solid perusal!

Outputting a String
To output a string, like we have done in previous lessons, use the PHP echo function
...


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

Display:
Hello!

I love using PHP!
In the above example we output "Hello!" without a hitch
...
To do this we
simply put the
at the beginning of the string and closed it at the end of the string
...
However, you must be careful when using HTML
code or any other string that includes quotes! The echo function 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 slash
...
e
...


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

PHP Code:
// This won't work because of the quotes around specialH5!
echo "
I love using PHP!
";
// OK because we escaped the quotes!
echo "
I love using PHP!
";
// OK because we used an apostrophe '
echo "
I love using PHP!
";
?>

If you want to output a string that includes quotations, either use an apostrophe ( ' ) or escape the
quotations by placing a slash in front of it ( \" )
...


Echoing Variables
Echoing variables is very easy
...

Below is the correct format for echoing a variable
...
My name is: ";
$my_number = 4;
$my_letter = a;
echo $my_string;
echo $my_number;
echo $my_letter;
?>

Display:
Hello Bob
...
By doing such a conjunction you save yourself from
having to do a large number of echo statements
...

)
...


PHP Code:
$my_string = "Hello Bob
...
"Bobettta"
...
Who are you? "
...
$newline;
echo "Hi, I'm Bob
...
$my_string
...
My name is: Bobetta
Hi, I'm Bob
...
My name is:
Hi, I'm Bob
...
My name is: Bobetta
This combination can be done multiple times, as the example shows
...


PHP - Strings
In the last lesson, PHP Echo, we used strings a bit, but didn't talk about them in depth
...


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
...


PHP Code:
$my_string = "Tizag - Unlock your potential!";
echo "Tizag - 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 function and not be stored
...
They look identical just as we thought
...


PHP Code:
$my_string = 'Tizag - Unlock your potential!';
echo 'Tizag - 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 \
...

Double-quotes allow for many special escaped characters to be used that you cannot do with a single-quote
string
...


PHP Code:
$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
...
A tab, newline, and carriage return are all examples of extra (ignorable) white space
...
PHP
introduces a more robust string creation tool called heredoc that lets the programmer create multi-line strings
without using quotations
...
com
Webmaster Tutorials
Unlock your potential!
TEST;

echo $my_string;

There are a few very important things to remember when using heredoc
...
In this example we chose TEST as
our identifier
...
In this example that
was TEST;
The closing sequence TEST; must occur on a line by itself and cannot be indented!

Another thing to note is that when you output this multi-line string to a web page, it will not span multiple
lines because we did not have any
tags contained inside our string! Here is the output made from the
code above
...
com Webmaster Tutorials Unlock your potential!
Once again, take great care in following the heredoc creation guidelines to avoid any headaches
...
You have already seen the string concatenation operator "
...

There are many operators used in PHP, so we have separated them into the following categories to make
it easier to learn them all
...
Such an assignment of value is done with the "=", or equal character
...
Assignments can also be used in conjunction
with arithmetic operators
...
$addition
...
$subtraction
...
$multiplication
...
$division
...
$modulus

...

In this case it was 5 / 2, which has a remainder of 1
...
Modulus is the remainder after the division operation has been
performed
...


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
...

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 "
...


PHP Code:
$a_string = "Hello";
$another_string = " Billy";
$new_string = $a_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
...
Say you want to increment a counter by 1, you would have:



$counter = $counter + 1;

However, there is a shorthand for doing this
...
The downside to this
combination operator is that it reduces code readability to those programmers who are not used to such an
operator
...
In general, "+=" and "-=" are the
most widely used combination operators
...
=

Concatenate Equals $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
...
Our PHP code below will display the difference
...
$x++;
echo "
The value of x after the post-plusplus is "
...
++$x;
echo "
The value of x after the pre-plusplus is "
...
However, with the pre-increment "++$x" the variable does
reflect the addition immediately
...
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 by the browser
...
However, PHP's comments are different in that they will not be displayed to
your visitors
...
This makes PHP
comments only useful to PHP programmers
...


HTML Code:


PHP Comment Syntax: Single Line Comment
While there is only one type of comment in HTML, PHP has two types
...
The single line comment tells the interpreter to ignore everything that occurs on that line
to the right of the comment
...


PHP Code:
echo "Hello World!"; // This will print out Hello World!
echo "
Psst
...
You can't see my PHP comments!
Notice that a couple of our echo statements were not evaluated because we commented them out with the
single line comment
...


PHP Comment Syntax: Multiple Line Comment
Similiar to the HTML comment, the multi-line PHP comment can be used to comment out large blocks of
code or writing multiple line comments
...


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

Display:
Hello World!

Good Commenting Practices
One of the best commenting practices that I can recommend to new PHP programmers is
...
However, do you really believe that you will remember exactly what you were
thinking when looking at this code a year or more down the road?
Let the comments permeate your code and you will be a happier PHPer in the future
...


The Include Function
Without understanding much about the details of PHP, you can save yourself a great deal of time with the
use of the PHP include function
...

Why is this a cool thing? Well, first of all, this means that you can type up a common header or menu file
that you want all your web pages to include
...


An Include Example
Say we wanted to create a common menu file that all our pages will use
...
php" extension
...
php"
...
php Code:


About Us Contact Us


Save the above file as "menu
...
Now create a new file, "index
...
php"
...


index
...
php"); ?>

This is my home page that uses a common menu to save me time when I add
new pages to my website!





Display:
Home - About Us - Links - Contact Us

This is my home page that uses a common menu to save me time when I add new pages
to my website!
And we would do the same thing for "about
...
php", and "contact
...
Just think how terrible it
would be if you had 15 or more pages with a common menu and you decided to add another web page to that
site
...
php" and all your problems are solved
...


What do Visitors See?
If we were to use the include function to include a common menu on each of our web pages, what would
the visitor see if they viewed the source of "index
...
php to a Visitor:


About Us Contact Us

This is my home page that uses a common menu to save me time when I add
new pages to my website!





The visitor would actually see all the HTML code as one long line of HTML code, because we have not
inserted any new line characters
...
We will be
discussing new line characters later
...
Include is quite useful when you want to include the same PHP, HTML, or text
segment on multiple pages of a website
...

The next lesson will talk about a slight variation of the include function: the require function
...
Read the next lesson to find out
why!

PHP Require Function
Just like the previous lesson, the require function is used to include a file into your PHP code
...


Require vs Include
When you include a file with the include function and PHP cannot find it you will see an error message like
the following:

PHP Code:
include("noFileExistsHere
...
php): failed to open stream: No such file or directory in
/home/websiteName/FolderName/tizagScript
...
php' for inclusion (include_path='
...
php on line 2
Hello World!
Notice that our echo statement is still executed, this is because a Warning does not prevent our PHP
script from running
...


PHP Code:
require("noFileExistsHere
...
php): failed to open stream: No such file or directory in
/home/websiteName/FolderName/tizagScript
...
php'
(include_path='
...
php on line 2
The echo statement was not executed because our script execution died after the require function
returned a fatal error! We recommend that you use require instead of include because your scripts should not
be executing if necessary files are missing or misnamed
...
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
...
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
...
Imagine that on January
1st you want to print out "Happy New Year!" at the top of your personal web page
...

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
...
The PHP if statement tests to see if a value is true, and if it is a segment of
code will be executed
...


PHP Code:
$my_name = "someguy";
if ( $my_name == "someguy" ) {
echo "Your name is someguy!
";
}
echo "Welcome to my homepage!";

Display:
Your name is someguy!
Welcome to my homepage!
Did you get that we were comparing the variable $my_name with "someguy" to see if they were equal? In
PHP you use the double equal sign (==) to compare values
...
Let's go a bit
more in-depth into this example to iron out the details
...

We next used a PHP if statement to check if the value contained in the variable $my_name was equal
to "someguy"
The comparison between $my_name and "someguy" 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
...

$my_name is indeed equal to "someguy" so the echo statement is executed
...
Say that we
changed the above example to:

PHP Code:
$my_name = "anotherguy";
if ( $my_name == "someguy" ) {
echo "Your name is someguy!
";
}
echo "Welcome to my homepage!";

Display:
Welcome to my homepage!
Here the variable contained the value "anotherguy", which is not equal to "someguy"
...
When used properly, the if
statement is a powerful tool to have in your programming arsenal!

If/Else Conditional Statment
Has someone ever told you, "if you work hard, then you will succeed"? And what happens if you do not
work hard? Well, you fail! This is an example of an if/else conditional statement
...

Else, if you do not work hard, then you will fail
...
With an if statement this is easy
...
If the condition is true, then take them to the "Insert Your Name" page, else let her view the
website as normal because you have already asked her for her name in the past
...
Here's the basic form
of an if/else statement in PHP
...








We first made a PHP variable called $number_three and set it equal to 3
...
To do such a comparison we use "==",
which in English means "Is Equal To"
...

All code that is contained between the opening curly brace "{" that follows the if statement and the
closing curly brace "}" will be executed when the if statement is true
...


Execute Else Code with False
On the other hand, if the if statement was false, then the code contained in the else segment would have
been executed
...


PHP Code:
$number_three = 421;
if ( $number_three == 3 ) {
echo "The if statement evaluated to true";
} else {
echo "The if statement evaluated to false";
}

Display:
The if statement evaluated to false
The variable was set to 421, which is not equal to 3 and the if statement was false
...


PHP - Elseif
An if/else statement is great if you only need to check for one condition
...
Tanner,
or a regular employee? To check for these different conditions you would need the elseif statement
...
e
...
Just like
an if statement, an elseif statement also contains a conditional statement, but it must be preceded by an if
statement
...

When PHP evaluates your If
...
else statement it will first see if the If statement is true
...
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!)
...


PHP - Using Elseif with If
...
Imagine we have a simpler version of the problem described above
...
Tanner
...


PHP Code:
$employee = "Bob";
if($employee == "Ms
...


PHP Code:
$employee = "Bob";
if($employee == "Ms
...
Tanner", which evaluated to false
...
$employee did in fact equal "Bob" so the phrase "Good Morning Sir!" was
printed out
...
However,
there are times when an if statement is not the most efficient way to check for certain conditions
...
In this example you might have 20 different locations that you would have to check
with a nasty long block of If/ElseIf/ElseIf/ElseIf/
...
This doesn't sound like much fun to code, let's
see if we can do something different
...
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
...


PHP Switch Statement Example
In our example the single variable will be $destination and the cases will be: Las Vegas, Amsterdam,
Egypt, Tokyo, and the Caribbean Islands
...
It found it and proceeded to execute the code
that existed within that segment
...
This break prevents
the other cases from being executed
...
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
...


PHP Switch Statement: Default Case
You may have noticed the lack of a place for code when the variable doesn't match our condition
...

It's usually a good idea to always include the default case in all your switch statements
...
Note: there is no case before default
...
A very common
application of PHP is to have an HTML form gather information from a website's visitor and then use PHP to do
process that information
...

Imagine we are an art supply store that sells brushes, paint, and erasers
...

Note: This is an oversimplified example to educate you how to use PHP to process HTML form
information
...


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
...
This file
should be saved as "order
...


order
...
Next we must
alter our HTML form to specify the PHP page we wish to send this information to
...


order
...
php" method="post">

Quantity:




Now that our "order
...
php" file which will
process the HTML form information
...
Using an
associate array (this term is explained in the array lesson), we can get this information from the $_POST
associative array
...
The name of this file is "process
...


process
...
$quantity
...

";
echo "Thank you for ordering from Tizag Art Supplies!";
?>


As you probably noticed, the name in $_POST['name'] corresponds to the name that we specified in our
HTML form
...
html" and "process
...
If
someone selected the item brushes and specified a quantity of 6, then the following would be displayed on
"process
...
php Code:
You ordered 6 brushes
...
Let us step through it to be sure you understand what was
going on
...

2
...

4
...
html" that had two input fields specified, "item" and "quantity"
...
php" and set the method to "post"
...
php" get the information that was posted by setting new variables equal to the values
in the $_POST associative array
...


Remember, this lesson is only to teach you how to use PHP to get information from HTML forms
...


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

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
...
So don't
give up if you functions confuse you at first!

Creating Your First PHP Function
When you create a function, you first need to give it a name, like myCompanyMotto
...

The actual syntax for creating a function is pretty self-explanatory, but you can be the judge of that
...
You do this by typing the keyword function followed by
your function name and some other stuff (which we'll talk about later)
...
Note: We still have to fill in the code for
myCompanyMotto
...
Do you see the curly braces in the above example "{ }"? These braces define where our function's
code goes
...


Using Your PHP Function
Now that you have completed coding your PHP function, it's time to put it through a test run
...
Let's do two things: add the function code to it and use the function twice
...
com
";
echo "Well, thanks for stopping by!
";
echo "and remember
...
com
";
myCompanyMotto();
echo "Well, thanks for stopping by!
";
echo "and remember
...
com
We deliver quantity, not quality!
Well, thanks for stopping by!
and remember
...
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
...

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
...

Our parameter will be the person's name and our function will concatenate this name onto a greeting
string
...


PHP Code with Function:
function myGreeting($firstName){
echo "Hello there "
...
"!
";
}
?>

When we use our myGreeting function we have to send it a string containing someone's name, otherwise
it will break
...


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

Display:
Hello
Hello
Hello
Hello

there
there
there
there

Jack!
Ahmed!
Julie!
Charles!

It is also possible to have multiple parameters in a function
...
Let's modify our function to also include last names
...
$firstName
...
"!
";
}
myGreeting("Jack", "Black");
myGreeting("Ahmed", "Zewail");
myGreeting("Julie", "Roberts");
myGreeting("Charles", "Schwab");
?>

Display:
Hello
Hello
Hello
Hello

there
there
there
there

Jack Black!
Ahmed Zewail!
Julie Roberts!
Charles Schwab!

PHP Functions - Returning Values
Besides being able to pass functions information, you can also have them return a value
...
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
...
Something like:



$myVar = somefunction();

Let's demonstrate this returning of a value by using a simple function that returns the sum of two integers
...
$myNumber
...
$myNumber
...
However, when we
set $myNumber equal to the function mySum, $myNumber is set equal to mySum's result
...
If you are having a
hard time understanding lessons, the best piece of advice would be to do your best the first time, then be sure
to come back tomorrow and next week and see if it makes anymore sense
...


PHP - Arrays
An array is a data structure that stores one or more values in a single value
...


PHP - A Numerically Indexed Array
If this is your first time seeing an array, then you may not quite understand the concept of an array
...

How would you go about this?
It wouldn't make much sense to have to store each name in its own variable
...
This can be done, and we show you how below
...
The keys were the numbers
we specified in the array and the values were the names of the employees
...
The general form for setting the key of an array equal to a value
is:



$array[key] = value;

If we wanted to reference the values that we stored into our array, the following PHP code would get the
job done
...
$employee_array[0]
...
$employee_array[2]
...

Above we showed an example of an array that made use of integers for the keys (a numerically indexed array)
...


PHP - Associative Arrays
In an associative array a key is associated with a value
...
Instead, we could use the
employees names as the keys in our associative array, and the value would be their respective salary
...
$salaries["Bob"]
...
$salaries["Sally"]
...
$salaries["Charlie"]
...
$salaries["Clare"];

Display:
Bob is being paid - $2000
Sally is being paid - $4000
Charlie is being paid - $600
Clare is being paid - $0
Once again, the usefulness of arrays will become more apparent once you have knowledge of for and
while loops
...
Deleting spam email, sealing 50 envelopes, and going to work
are all examples of tasks that are repeated
...
Most often these repetitive tasks are conquered in the loop
...
Before we
show a real example of when you might need one, let's go over the structure of the PHP while loop
...
This logical check is the same as the one that appears in a PHP if statement to determine if it is true or
false
...
Here is the break down of how a
while loop functions when your script is executing:
1
...

3
...


The conditional statement is checked
...
If it is false, then (4) occurs
...

The process starts again at (1)
...

If the conditional statement is false, then the code within is not executed and there is no more looping
...


A Real While Loop Example
Imagine that you are running an art supply store
...
You sell brushes at a flat rate, but would like to display how much different quantities
would cost
...

You know that a while loop would be perfect for this repetitive and boring task
...


Pseudo PHP Code:
$brush_price = 5;
$counter = 10;
echo "";
echo "";
echo "";
while ( $counter <= 100 ) {
echo "";
$counter = $counter + 10;
}
echo "
QuantityPrice
";
echo $counter;
echo "
";
echo $brush_price * $counter;
echo "
";

Display:
Quantity Price
10

50

20

100

30

150

40

200

50

250

60

300

70

350

80

400

90

450

100

500

Pretty neat, huh? The loop created a new table row and its respective entries for each quantity, until our
counter variable grew past the size of 100
...
Let's review what is going on
...

2
...

4
...

6
...


We first made a $brush_price and $counter variable and set them equal to our desired values
...

The while loop conditional statement was checked, and $counter (10) was indeed smaller or equal to
100
...

We then added 10 to $counter to bring the value to 20
...

After the loop had completed, we ended the table
...
You have
to place slashes before quotations if you do not want the quotation to act as the end of the echo statement
...

With proper use of loops you can complete large tasks with great ease
...
The common tasks that are covered by
a for loop are:
1
...

3
...


Set a counter variable to some initial value
...

Execute the code within the loop
...


The for loop allows you to define these steps in one easy line of code
...
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
...
A semicolon is needed
because these are separate expressions
...

Here is the example of the brush prices done with a for loop
...
However, the for loop is somewhat more compact and would be preferable in this
situation
...


PHP For Each Loop
Imagine that you have an associative array that you want to iterate through
...

In plain english this statement will do the following:



For each item in the specified array execute this code
...


PHP For Each: Example
We have an associative array that stores the names of people in our company as the keys with the values
being their age
...


PHP Code:
$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";
foreach( $employeeAges as $key => $value){
echo "Name: $key, Age: $value
";
}

Display:
Name:
Name:
Name:
Name:
Name:

Lisa, Age: 28
Jack, Age: 16
Ryan, Age: 35
Rachel, Age: 46
Grace, Age: 34

The syntax of the foreach statement is a little strange, so let's talk about it some
...

The operator "=>" represents the relationship between a key and value
...
In our example we named the key $key and the value $value
...
Below our example does this and notice how the output is identical
because we only changed the variable names that refer to the keys and values
...
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
...

On the other hand, a do-while loop always executes its block of code at least once
...


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
...
I love cookies! *munch munch munch*";
}

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
...
I love cookies! *munch munch munch*";
} while ($cookies > 1);

Display:
Mmmmm
...
I love cookies!" was executed even though the conditional statement was
false
...
In that lesson we opted to use the the post method for submitting, but we could have also chosen
the get method
...


POST - Review
In our PHP Forms Lesson we used the post method
...
php" method="post">
:

Female::

Please choose type of residence::

Steak::

Pizza::

Chicken::/>

Textareas
In reality, textareas are oversized input fields
...
PHP relys on this attribute to display the textarea
...

:


Drop Down Lists & Selection Lists
These two forms act very similar to the already discussed radio and checkbox selections
...


Code:

...
High">Jr
...
As far as names go, you can copy the ones shown or simply
make up your own, just be sure you remember what they are
...


Display:

First Name:
Last Name:
Gender:
Male:
Female:
Favorite Food:
Steak:
Pizza:
Chicken:
Enter your favorite quote!

Select a Level of Education:
Jr
...
Now's the time to throw it into the existing code
...

Code:


...
It's a superglobal of PHP and it's one that is
great to have memorized
...
The best way
to do this, is to make variables for each element in our form, so we can output this data at will, using our own
variable names
...


Code:
$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
$gender = $_POST["gender"];
$food = $_POST["food"];
$quote = $_POST["quote"];
$education = $_POST["education"];
$TofD = $_POST["TofD"];
?>
All we are doing here is making easier variable names for our form output
...


$PHP_SELF; - Submission
For the form action, we will call PHP's $PHP_SELF; array
...
Basically, we are setting up the form to call "formexample
...
Here's a glypmse of how to do
just that
...

$quote = $_POST["quote"];
$education = $_POST["education"];
$TofD = $_POST["TofD"];
?>


Personal INFO




...
However, we need to adjust
things so that once the data has been submitted we are directed to the results
...
php file that recieves our HTML form data
...
This is a practical method when entering information into
databases as you learn more
...


Code:

$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
$gender = $_POST["gender"];
$food = $_POST["food"];
$quote = $_POST["quote"];
$education = $_POST["education"];
$TofD = $_POST["TofD"];
?>


Personal INFO



First Name:name="Fname">

Last Name:name="Lname">

Gender:

Male:

Female:

Please choose type of residence:

Steak:

Pizza:

Chicken:/>


Select a Level of Education:



Select your favorite time of day:






Page Display
At this point we have a completed form with correct action and submission
...
Before the user submits any
information
...

PHP offers an excellent way to create this effect using an if statement
...
php file
...
(feel free
to be creative here) We use the else clause of our if statement to direct the users to our results section
...




} else {
echo "Hello, "
...
$Lname
...
$gender
...
"
";
}
echo ""
...
"

";
echo "You're favorite time is "
...
", and you passed
"
...
"!
";
}
?>

Here's the completed code

Code:
$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
$gender = $_POST["gender"];
$food = $_POST["food"];
$quote = $_POST["quote"];
$education = $_POST["education"];
$TofD = $_POST["TofD"];
if (!isset($_POST['submit'])) { // if page is not submitted to
itself echo the form
?>


Personal INFO



First Name:name="Fname">

Last Name:name="Lname">

Gender:

Male:

Female:

Please choose type of residence:

Steak:

Pizza:

Chicken:/>


Select a Level of Education:



Select your favorite time of day:





} else {
echo "Hello, "
...
$Lname
...
$gender
...
"
";
}
echo ""
...
"

";
echo "You're favorite time is "
...
", and you passed

"
...
"!
";
}
?>

Here is the completed form formexample
...
High

Select your favorite time of day:
Morning
Day
Night
submit


Title: Php work book
Description: this php notes is for better understanding of students. this helps every one to gain knowledge on php. each and every topic explained with example so that learnig is made easy.