Professional Documents
Culture Documents
PHP is:
– Server-Side Scripting Language
– Used for Web Development
– Generate Dynamic Web Pages
PHP Requirements:
Computer with PHP installed
Text editing application
Steps:
<html>
<body>
<? php
echo "PHP: Hypertext Preprocessor";
?>
</body>
</html>
=========================================================================================
- aebihis 1
PHP: Hypertext Preprocessor
8. In the address bar, type: localhost/aiza/testing.php (for example) to view the result.
=========================================================================================
- aebihis 2
PHP: Hypertext Preprocessor
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.
=========================================================================================
- aebihis 3
PHP: Hypertext Preprocessor
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
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.
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.";
?>
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
Output:
String Variables
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.
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
Hello World!
Concatenation
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
Example: Output:
<?php
echo strlen("Hello world!"); 12
?>
=========================================================================================
- aebihis 7
PHP: Hypertext Preprocessor
strpos() function
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");
?>
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
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.
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.
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
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.
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
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.
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).
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.
Output:
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
=========================================================================================
- aebihis 13
PHP: Hypertext Preprocessor
=========================================================================================
- aebihis 14
PHP: Hypertext Preprocessor
- 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.
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:
An if statement can be read as: if the condition is true, perform this stuff, otherwise ignore this stuff.
Output:
=========================================================================================
- aebihis 15
PHP: Hypertext Preprocessor
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.
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;
}
Output:
=========================================================================================
- aebihis 19
PHP: Hypertext Preprocessor
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.
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.
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.
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:
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:
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
Output:
Example: breaknested.php
=========================================================================================
- aebihis 28
PHP: Hypertext Preprocessor
Output:
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:
Output:
=========================================================================================
- aebihis 30