You are on page 1of 30

PHP: Hypertext Preprocessor

LECTURE 1: Intro to PHP Programming

– stands for PHP: Hypertext Preprocessor.


- is a widely-used open source general-purpose scripting language that is
especially suited for web development and can be embedded into HTML.
- was originally created by Rasmus Lerdorf in 1995.

PHP is:
– Server-Side Scripting Language
– Used for Web Development
– Generate Dynamic Web Pages

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
 allow creation of shopping carts for e-commerce websites

PHP Requirements:
 Computer with PHP installed
 Text editing application

Steps:

1. Double-click the icon of XAMPP .


2. The XAMPP Control Panel Application will be display. Click the Start button of Apache and
MySql to run the application.

3. In Notepad or Notepad++, type the following (basic structure of PHP):

<html>
<body>
<? php
echo "PHP: Hypertext Preprocessor";
?>
</body>
</html>

4. Save your work.


5. Create your own folder in saving your file; the file extension will be .php (e.g. testing.php):

=========================================================================================
- aebihis 1
PHP: Hypertext Preprocessor

6. Click the Save button.


7. In running your program, open the HTML editor.

8. In the address bar, type: localhost/aiza/testing.php (for example) to view the result.

(folder name) (filename)

=========================================================================================
- aebihis 2
PHP: Hypertext Preprocessor

What is a PHP File?


 may contain text, HTML tags and scripts
 are returned to the browser as plain HTML
 have a file extension of ".php", ".php3", or ".phtml"
.php3 – which means the server has version3 of the php module loaded for use.
.phtml – check with your host on which one they require or just test out each type.

PHP Syntax
1. PHP Script

A PHP scripting block always starts with <?php and ends with ?>.

<? php

?>

2. Save the file of PHP and find the directory of htdocs to save there. The file extension in every PHP
file is .php
3. In the PHP script, type the statement inside the start tag and end tag.
Example: echo "Hello World!";

Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another.

There are two basic statements to output text with PHP:


1. echo – does not return a value, but has been considered as a faster executed command.
2. print – can return a true/false value. This may be helpful during a script execution of
some sort.

print and echo


- both called language constructs
- are commands used to output information to the visitors screen (on the web page)

4. In every changes in the files Save the files again.


5. Test / run the file.

=========================================================================================
- aebihis 3
PHP: Hypertext Preprocessor

6. Display the output.

Hello World!

Another example: Output:


<?php
print "Hello World!"; Hello World!
echo "Hello World!"; Hello World!
?>

If you have <br/> in the statement, it is called a line break or new line

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

Note: The file must have a .php extension. If the file has a .html extension, the PHP code will not
be executed.

If you need to use quotes within your value area and have them show up on the web page, you will have to
"escape" them. This is so the coding does not get confused on which quotes are the real ones and which ones
are for display.

Example: Output:
<?php Hello from "another" World!
print "Hello from \"another\" World!";
?>

Variables

- used for storing a values, like text strings, numbers or arrays.


- it can be used over and over again in your script

All variables in PHP start with a $ sign symbol. The correct way of setting a variable in PHP:

$var_name = value;

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

Rules in naming variable/s:


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

In PHP all the variables begin with a dollar sign "$" and the value can be assigns using the "=" operator.
The dollar sign is not technically part of the variable name, but it is required as the first character for the PHP

=========================================================================================
- aebihis 4
PHP: Hypertext Preprocessor

parser to recognize the variable as such. Another important thing in PHP is that all the statements must end with
a semicolon ";".

Example:
<? php
$name="Aiza";
$age=18;
echo "My name is $name and I am $age years old.";
?>

Here is some code creating and assigning values to a couple of variables:

Example:

<?php
//Commented lines starting with the double
//forward slash will be ignored by PHP
//First we will declare a few variables
//and assign values to them

$myText = "Have a nice day!";


$myNum = 5;

//Note that myText is a string and myNum is numeric.


//Next we will display these to the user.
echo $myText;
//To concatenate strings in PHP, use the '.' (period) operator
echo "My favorite number is ". $myNum;
?>

Output:

Have a nice day! My favorite number is 5

String Variables

- A string variable is used to store and manipulate text.


- used for values that contain characters.

Below, the PHP script assigns the text "Hello World" to a string variable called $txt:

Example: Output:
<?php
$txt="Hello World"; Hello World
echo $txt;
?

Comments

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

=========================================================================================
- aebihis 5
PHP: Hypertext Preprocessor

Programmers and individuals should invest their time into commenting for three primary reasons:
1. Employment – others may know how to operate or modify your program correctly.
EXAMPLE: If you are working for an employer, or are planning to release your source code to
the public, you will need to make use of comments. Employers demand it because if they were
to lose you as an employee, they would have to hire someone new to peruse your code.
2. Saving time – projects grow in scale; programmers will forget where you place certain bits of
code or even what large blocks of code do.
EXAMPLE: Programmers do without comments at this stage, claiming they can remember the
programs they make. In reality, a programmer will often come back to a certain code block
months into the future, and quickly find they will need to take a few hours to reread their code
and comment it properly.
3. Troubleshooting – more intelligently, programmers use PHP comments to troubleshoot their
applications. When trying to find which code block is causing an error, programmers can quickly
section out new additions to the application with a comment block to see if the error subsides.
If it does, that’s where the error lies. If not, the error lies elsewhere.

Two Types of Comments:

1. single-line comment
- //statement
- to make a 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.
- used for quick notes about complex and confusing code or to temporarily remove a line of PHP
code.

Example:

<?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";
?>

Output:

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

2. multiple-line comment
- /* statement/s */
- to make a large comment block.
- 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 " */ ".

Example:

<?php
/* This Echo statement will print out my message to the
the place in which I reside on. In other words, the World.
*/

=========================================================================================
- aebihis 6
PHP: Hypertext Preprocessor

echo "Hello World!";


/* echo "My name is Humperdinkle!";
echo "No way! My name is Uber PHP Programmer!";
*/
?>
Output:

Hello World!

Concatenation

- concatenation operator (.) is used to put two string values together.

To concatenate two string variables together, use the concatenation operator:

Example 1: Output:
<?php Hello World! What a nice day!
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>

Example 2:
<?php
echo "Hello"."World! <br/>";
//Concatenation slows down the process because of PHP must add strings
together
echo "Hello","<br/>";
echo "World!","<br/>";
//Calling echo multiple times still isn’t good as using echo parameters
solely
echo "Hello","World!","<br/>";
//Correct! In a large loop, this could save of seconds in the long run!
?>

Output:

HelloWorld!
Hello
World!
HelloWorld!

strlen() function

- strlen() function is used to return the length of a string.

Let's find the length of a string:

Example: Output:
<?php
echo strlen("Hello world!"); 12
?>

=========================================================================================
- aebihis 7
PHP: Hypertext Preprocessor

strpos() function

- strpos() function is used to search for a character/text within a string.

Parameters:
 string – it specifies string to search
 find – it specifies string to find
 start – it specifies were to begin the search

Example:

Let's see if we can find the string "world" in our string: Output:
start
6
<?php 1 2 3 45 6
echo strpos("Hello world!","world");
?>
string find

If a match is found, this function will return the character position of the first match.

Example 1: Output:
<?php
11
echo strpos("Hello world!","!");
?>

Example 2: Output:
<?php
2
echo strpos("Hello world!","l");
?>

If no match is found, it will return FALSE.

Example 3: Output:
<?php
echo strpos("Hello world!","worlds");
?>

Example 4: Output:
<?php
echo strpos("Hello world!",".");
?>
If adding additional parameter, it will display PARSE ERROR.

=========================================================================================
- aebihis 8
PHP: Hypertext Preprocessor

LECTURE 2: PHP Operators

Operators
- are a set of symbols that perform mathematical and other operations.
- These symbols are what we use to tell the PHP interpreter how to perform a calculation on the data
we are working with.

PHP Operator Precedence

Below is a table of PHP operator precedence. This list goes from highest precedence to lowest. Operators on
the same line have a similar precedence. Remember that an operator with a higher precedence will always be
evaluated before one with a lower precedence.

Of course, operations which are placed in brackets automatically have the highest precedence.

Operator Description
++ -- increment/decrement
(int) (float) (string) (array) (object) (bool) casting
! logical "not" (inverse)
*/% arithmetic operator
+-. arithmetic and string
< <= > >= <> comparison
== != === !== comparison
&& logical "and"
|| logical "or"
= += -= *= /= .= %= assignment
and logical "and"
xor logical "xor"
or logical "or"

The above table is very important to know. Note that you might get incorrect results when you do calculations
if you do not take note of the precedence of the operators you are using. Remember that you can use regular
brackets () to enforce a particular precedence.

Six Basic Types of PHP Operators

1. Arithmetic Operators
- these operators carry out mathematical functions.

=========================================================================================
- aebihis 9
PHP: Hypertext Preprocessor

Example#1: arith1.php

Output:

2. Assignment Operators
- these operators store values in variables.
- 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.

Example#1: ass1.php (the basic assignment operation in PHP uses the equal sign ( = ) )

Output:

=========================================================================================
- aebihis 10
PHP: Hypertext Preprocessor

Example#2: ass2.php Output:

3. Comparison Operators
- these operators compare values.
- are used to check the relationship between variables and/or values.
- are used inside conditional statements and evaluate to either true or false.

Example #1: comp1.php

Output:

If we were to output the result of a comparison operation directly we would get a 1 for true and no output for false.

4. Logical Operators
- these operators perform Boolean logic and returns true or false.

=========================================================================================
- aebihis 11
PHP: Hypertext Preprocessor

Operator Description Example


&& and x=6
y=3
(x < 10 && y > 1) returns true
|| or x=6
y=3
(x==5 || y==5) returns false
! not x=6
y=3
!(x==y) returns true

The PHP logical operators are used just like the PHP comparison operators as they return Boolean values
as their result.

5. Increment/Decrement
- these operators’ increment or decrement a number value.

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 "shorterhand" 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 (pre/post increment and pre/post decrement).

Example #1: unary1.php

Output:

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.

=========================================================================================
- aebihis 12
PHP: Hypertext Preprocessor

6. String Operators
- these operators join strings together.
- There is really only one specific string operator, although the string object has many methods you
can access. The only string operator is the concatenation operator.

Concatenation operator
- it is represented by the period ( . )
- is a special case of operator.
- it is an overloaded operator, since it serves more than once function depending on context.
- it concatenates (join) strings, but it also serves as a decimal point and a separator for object
property relationships.

When working with strings, the comparison operators test on a character by character basis, so two strings
that are the same except for some trailing spaces, or a difference in capitalization, will be treated as different
strings. This means that comparisons can get confusing. This is especially true of strings that contain numeric
values.

Example #1: string1.php

Output:

Example #2: string2.php

Output:

Practice: Evaluate and solve the following statements. Show your solution and put your final answer inside
the box.

1. ((f + l + j) > (m * f)) || (!A && (P || R)) True A = False D = False int e = 1
2. !(C && A || L) || ((C && P) || (k * f) + j < f * f) False P = True R = True int j = 5

C = False int f = 3 int k = 3

L = True int l = 1 int m = 6

=========================================================================================
- aebihis 13
PHP: Hypertext Preprocessor

Given: ((f + l + j) > (m * f)) || (!A && (P || R))

Given: !(C && A || L) || ((C && P) || (k * f) + j < f * f)

=========================================================================================
- aebihis 14
PHP: Hypertext Preprocessor

LECTURE 3: Conditional Statement

- are the set of commands used to perform different actions based on different conditions.
- are evaluated as either being true or false.
- There are several conditional statements in PHP, and it is up to you as a programmer to determine
which approach to take in a given situation.

There are two basic concepts that will help you build conditions.
1. condition always returns true or false.
2. as long as something has (or returns) a value — and almost everything in PHP does — it can be used
in a condition.

In PHP we have the following conditional statements:


 if statement - use this statement to execute some code only if a specified condition is true
 if...else statement - use this statement to execute some code if a condition is true and another code
if the condition is false
 if...elseif....else statement - use this statement to select one of several blocks of code to be
executed
 switch statement - use this statement to select one of many blocks of code to be executed

if statement
- execute certain code only if a specified condition is true
- allows execution of fragments of code, all depending on what condition has been meet.

The simplest conditional statement is an if statement. For example, if it is morning, the sun is rising.

Syntax:

if (condition) code to be executed if condition is true;

An if statement can be read as: if the condition is true, perform this stuff, otherwise ignore this stuff.

Example #1: if1.php

Output:

=========================================================================================
- aebihis 15
PHP: Hypertext Preprocessor

Example #2: if2.php

Output:

Notice that there is no ..else.. in this code. The code is executed only if the specified condition is true.

--- or ---
FileName: if22.php

Output:

The second if statement was false so the code within the curly braces was not executed. It is important to
note that if you are only executing a single statement based on the outcome of the if, you can omit the curly
braces.

if…else statement
- execute some code if a condition is true and another code if a condition is false.
- The else statement extends the if statement. Because the else statement cannot hold a comparison
expression, you can only make use of it in combination with an if statement. The else statement
executes code if the if statement’s comparison expression evaluates to false.

=========================================================================================
- aebihis 16
PHP: Hypertext Preprocessor

Syntax:
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

The first example decides whether a student has passed an exam with a pass mark of 57:

FileName: else1.php

Output:

PHP allows you to choose what action to take based upon the result of a condition. This condition can be
anything you choose, and you can combine conditions together to make for actions that are more complicated.
Here is a working example:

FileName: else2.php

Output:

=========================================================================================
- aebihis 17
PHP: Hypertext Preprocessor

if…elseif…else statement
- extends the else statement so that it can have a comparison expression. If the elseif condition is
true, it will (just like the if statement) execute the statements within its curly brackets.
- used to select one of several blocks of code to be executed.
- it allows us to check as many conditions as we like and then take the appropriate action for any condition
that is met.

Syntax:
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

If no conditions are true then it will evaluate the final else. Note though, that this final else does not have to be
a part of our if-elseif block like in a situation where we do not want to perform an action when no conditional
match is met.

The program will test each condition in sequence until:


 It finds one that is true. In this case it executes the code for that condition.
 It reaches an else statement. In which case it executes the code in the else statement.
 It reaches the end of the if...elseif...else structure. In this case it moves to the next statement
after the conditional structure.

Example #1: elseif1.php

Output:

switch statement
- separates our code into blocks; each block representing the code to be executed if the condition which
is being checked for is true.
- allows a program to evaluate an expression and attempt to match the expression's value to a case label.
If a match is found, the program executes the associated statement.

=========================================================================================
- aebihis 18
PHP: Hypertext Preprocessor

- work the same as if statements. However the difference is that they can check for multiple values. Of
course you do the same with multiple if…else statements, but this is not always the best approach.

Syntax:
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}

Example #1: switch1.php

Output:

=========================================================================================
- aebihis 19
PHP: Hypertext Preprocessor

Example #2: switch2.php

Output:

This is because the meal variable was set to 'Burger' and under the case for 'Burger' is the instruction to
output 'We currently have a special on this'.

Use break to prevent the code from running into the next case automatically. The default statement is
used if no match is found.

Note: Beginning programmers should always include the break; to avoid any unnecessary confusion.

=========================================================================================
- aebihis 20
PHP: Hypertext Preprocessor

LECTURE 4: Looping

- in PHP are used to execute the same block of code a specified number of times.

So why do we use loops?


- There are hundreds and hundreds of reasons, the widest usage is probably to cycle through values of
some sort of data.

Example: You might be writing a messaging system in PHP, which would allow users of your website to
send private messages to each other once they register. You would write a MySQL query which would
pull all the user’s letter from the database. To show all the letters you would use a loop to show all the
rows of the query (all the separate messages) on a page.

In PHP we have the following looping statements:


 while - loops through a block of code if and as long as a specified condition is true
 do...while - loops through a block of code once, and then repeats the loop as long as a special condition
is true
 for - loops through a block of code a specified number of times
 foreach - loops through a block of code for each element in an array

while statement
- will execute a block of code if and as long as a condition is true.

Syntax:
while (condition)
{
code to be executed;
}

The following example (whileloop.php) demonstrates a loop that will continue to run as long as the variable
i is less than, or equal to 5. i will increase by 1 each time the loop runs:

Output:

=========================================================================================
- aebihis 21
PHP: Hypertext Preprocessor

Note: Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate.

do...while statement
- will execute a block of code at least once - it then will repeat the loop as long as a condition is true.

Syntax:
do
{
code to be executed;
}
while (condition);

The following example (dowhile.php) will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 5:

Output:

Imagine that you are running an art supply store. You would like to print out the price chart for number of brushes
and total cost. You sell brushes at a flat rate, but would like to display how much different quantities would cost.
This will save your customers from having to do the mental math themselves.

=========================================================================================
- aebihis 22
PHP: Hypertext Preprocessor

Example: dowhile3.php

Output:

The loop created a new table row and its respective entries for each quantity, until our counter variable grew
past the size of 100. When it grew past 100 our conditional statement failed and the loop stopped being used.
Let's review what is going on.

1. We first made a $brush_price and $counter variable and set them equal to our desired values.
2. The table was set up with the beginning table tag and the table headers.
3. The while loop conditional statement was checked, and $counter (10) was indeed smaller or equal to
100.
4. The code inside the while loop was executed, creating a new table row for the price of 10 brushes.
5. We then added 10 to $counter to bring the value to 20.
6. The loop started over again at step 3, until $counter grew larger than 100.
7. After the loop had completed, we ended the table.

You may have noticed that we placed slashes infront the quotations in the first echo statement. You have to
place slashes before quotations if you do not want the quotation to act as the end of the echo statement. This is
called escaping a character.

=========================================================================================
- aebihis 23
PHP: Hypertext Preprocessor

Escape sequences
- are small special functions.
- help in the visual presentation of the coding rather than the visual part on the web page.

The backslash character has several uses:


1. if it is followed by a non-alphanumeric character, it takes away any special meaning that character may
have. This use of backslash as an escape character applies both inside and outside character classes.
2. provides a way of encoding non-printing characters in patterns in a visible manner. There is no restriction
on the appearance of non-printing characters, apart from the binary zero that terminates a pattern, but
when a pattern is being prepared by text editing

Example:

\n New Line
\t Tab

for loop
- is used when we want to execute a block of code for certain number of times.
- is the most advanced of the loops in PHP.

Syntax:

for(initialize counter; condition until counter is reached; increment counter)


{
//execute block of code
}

for loop has three statements.


 initialize a counter variable to an number value;
Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
 set a condition (a max/min number value) until the counter is reached; and
Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE,
the loop ends.
 set a value by how much we want the counter variable to incremented/decremented by.
Mostly used to increment a counter (but can be any code to be executed at the end of the loop)

Note: Each of the parameters above can be empty, or have multiple expressions (separated by commas).

=========================================================================================
- aebihis 24
PHP: Hypertext Preprocessor

The following example (forloop.php) prints the text "Hello World!" five times:

Output:

Example: Print table with alternate colors using PHP For Loop (foralter.php)

=========================================================================================
- aebihis 25
PHP: Hypertext Preprocessor

Output:

foreach statement
- is used to loop through arrays. For every loop, the value of the current array element is assigned to
$value (and the array pointer is moved by one) - so on the next loop, you'll be looking at the next element.

Syntax:

foreach ($array as $value)


{
code to be executed;
}

The following example (reach123.php) demonstrates a loop that will print the values of the given array:

Output:

If you had tons of elements stored within an array, it will takes you quite some time to type in one by one.
Instead of typing it, you can use 'foreach' statement to loop all the value within an array.

=========================================================================================
- aebihis 26
PHP: Hypertext Preprocessor

Example: reachcolor.php

Output:

The foreach construct does not operate on the array itself, but rather on a copy of it. During each loop, the
value of the variable $value can be manipulated but the original value of the array remains the same.

We have an associative array that stores the names of people in our company as the keys with the values being
their age. We want to know how old everyone is at work so we use a foreach loop to print out everyone's
name and age.

The operator "=>" represents the relationship between a key and value

Example: reachage.php

Output:

=========================================================================================
- aebihis 27
PHP: Hypertext Preprocessor

Break and Continue Statements


Sometimes you may want to let the loops start without any condition, and allow the statements inside the
brackets to decide when to exit the loop. There are two special statements that can be used inside loops:
1. Break
- The PHP keyword break can be used to exit the current for, foreach, while, do-
while or switch.
- also accepts an optional integer parameter telling it how many nested blocks to break out of.

Here is an example (breakin.php) of using break from inside of a foreach loop:

Output:

And here is how to break out of multiple nested for loops:

Example: breaknested.php

=========================================================================================
- aebihis 28
PHP: Hypertext Preprocessor

Output:

Examples (breaknested2.php) below show how to use the break statement:

Output:

2. Continue
- is used with loops to skip the rest of the loop body and proceed with the next iteration.
- terminates execution of the block of statements in a while or for loop and continues execution
of the loop with the next iteration

=========================================================================================
- aebihis 29
PHP: Hypertext Preprocessor

Example: cont.php

Output:

Here is an example (cont2.php) of using continue in a while loop:

Output:

=========================================================================================
- aebihis 30

You might also like