0% found this document useful (0 votes)
13 views67 pages

Week 3 PHP Scripting-Part 1

bsygbh
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)
13 views67 pages

Week 3 PHP Scripting-Part 1

bsygbh
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/ 67

WEEK 3

PHP Scripting- Part 1


 Syntax
 Basics of PHP
 Data Types – Numbers and Strings
 Decision/Selection Control Structure
 Iteration/Repetition Control Structure
 User-defined Functions

1
Basic Syntax
 All PHP scripts are written in form of code blocks.
A PHP scripting block always starts with <?php and ends with ?>.

 On servers with shorthand support we are allowed to start a


scripting block with <? and end with ?>.

 Other style that can be used is by including PHP script in the


<script language = “PHP”>….....</script> block.

 For maximum compatibility, it is recommended that we use the


standard form:

<?php ….. ?>

• The file must have a .php extension. Otherwise, the PHP code will
not be executed.

2
Basic Syntax
 When PHP parses a file, it looks for opening and closing
tags, which tell PHP to start and stop interpreting the
code between them.

 Parsing in this manner allows PHP to be embedded in


all sorts of different documents, as everything outside of
a pair of opening and closing tags is ignored by the PHP
parser.

 Most
of the time you will see PHP embedded in HTML
documents, as in this example.

3
Basic Syntax
 A PHP file normally contains HTML tags, just like an HTML file, and
some PHP scripting code.
 A PHP scripting block can be placed anywhere in the document.

<html>
<head>
<?php
…….
?>
<title>Basic PHP </title>
</head>
<?php
……
?>
</html>
4
Basic Syntax
 The following page is to verify the availability of PHP on
your server with a lot of information about the PHP itself
and the server it's running on:
<html>
<body>
<?php
phpinfo();
?>
</body>
</html>
 Each code line in PHP must end with a semicolon (;). It
is a separator to distinguish a statement from another.
The phpinfo() is a PHP function.
 Note: It is also acceptable to create a PHP page without
including the HTML tags.
5
Comments
 Comments are explanatory remarks which are not executed by the
server.
 PHP supports three types of comments
 # this is a comment
 // this is also a comment
 /* this is a larger comment that
spans more than one line
…...*/
 Example
<?php
// This is a comment
/*
This is
a comment
block
*/ 6
?>
Variables
 Variable is used for storing a value like string, a number or an
array.
 When a variable is declared, it can be used repeatedly in PHP
script.
 All variables in PHP start with a $ sign symbol.
 The correct way to declare a variable in PHP:
$var_name = value;
 The rules of giving the name to a variable :
 After the dollar sign symbol ($), a variable name must start with a letter or
an underscore "_"
 A variable name can only contain alpha-numeric characters and
underscores (a-z, A-Z, 0-9, and _ )
 A variable name should not contain spaces. If a variable name uses
more than one word, it should be separated with an underscore
($my_var), or with capitalization ($myVar) 7
Variables
• Example
<?php
$txt = “Welcome to PHP World!";
$x = 5;
?>

• Valid and invalid PHP variables:

$myvar = "foo"; // Assigns the string 'foo'


badvar = "test"; // Invalid, no $ symbol
$another(test)var = "bad"; // Invalid, can't use ()
$php5 = "is cool"; // Correct Syntax
$5php = "is wrong"; // Invalid, starts with number
8
Variables
 PHP is a loosely typed language, a variable does not
need to be declared before a value is assigned to it.
 In PHP, the variable is declared automatically when you
use it.
 Also, the data type of a variable does not have to be
specified.
 PHP automatically converts the variable to the correct
data type, depending on its value.
 In a strongly typed programming language, you have to
declare (define) the type and name of the variable before
using it.

9
Data Types
 PHP basic data types are as follows:
integer - whole numbers
double - real numbers
string - strings of characters (values are
enclosed in quotes)
Boolean – true or false
 Others include array (a set or group of
variables of the same type) and object (class
instances )

10
Data Types
 Integers
 integer
values use three mathematical bases:
decimal (base 10), octal (base 8), and
hexadecimal (base 16 )
 examples:

$my_int = 50; /* Standard Decimal Notation */


$my_int = O62; /* Same number, Octal Notation
(starts with the letter O)*/
$my_int = 0x32; /* Hexadecimal Notation */

11
Data Types
 Doubles
 real numbers or numbers that have decimal point
 if the number is too big or too small, it can be represented using
exponential notation of the following form:
7.31e-4 (7.31 x 10-4 ) to represent 0.000731
1.625e5 (1.625 x105) to represent 162550
 where e stands for exponent (x10). The number before it is
called mantissa, and the number after it is the power of 10.
 examples:

$x = 0.00051; /* Standard Floating Point Notation */


$y = .051e-2; /* Exponential Notation of the same
number */

12
Type Casting
 Type casting in PHP means to treat a variable of one
type as if it was another (without actually changing its
type.)
 Implemented in the following form: (data_type)$variable
 For example:
$quantity = 0;
$amount = (double)$quantity;
 $quantity is initially set up as an integer with a value of zero.
 The next line treats $quantity as a double type and assigns its
value to $amount.
 $amount is now a double with a value of zero and $quantity is
still an integer with a value of zero.

13
Type Casting
• Type casts can also be automatic, such as adding a
double to an integer, the result will be a double even if it
is stored in the original integer variable.
• For example:
$int = 12;
$double = 10.37;
$int = $int + $double;
echo $int;

which will display:


22.37

14
Output Operations
 There are two basic statements to output text with PHP:
echo and print.
 Both are used to output one or more strings.
 The echo() is slightly faster than print(). The print()
returns true/false, but echo() does not.
 The parentheses are optional, they cannot be used for
more than one string.
 Syntax:
echo | print string;
echo | print string1, string2, …, stringn;
echo | print (string);
- string must be enclosed in quotes (single or double)
- more than one string must be separated by commas 15
Output Operations
HTML tags can also be included in the strings in
order to format the printed text.
Examples:
1)
<?php echo “Hello, there World!”; ?>
Output: Hello, there World!

2) Using HTML tags:


<?php
echo "This text<br>spans multiple<br>lines.";
?>
Output: This text
spans multiple
lines.
16
Output Operations
3) To print more than one parameter of strings:
<?php
echo “Hello there! ”, “How are you? ”, “Welcome.”;
?>
Output:
Hello there! How are you? Welcome.
4) To print the value of a variable:
<?php
$num = 25;
echo “The number is $num”;
?>
Output:
The number is 25

17
Output Operations
5) To show the difference of single and double quotes.
Single quotes will print the variable name, not the value:
<?php
$color = "red";
echo "Roses are $color";
echo "<br >";
echo 'Roses are $color';
?>
Output:
Roses are red
Roses are $color

18
Output Operations
 There is also the shortcut syntax of echo, which is as
follows:
<html>
<body>
<?php
$color = "red";
?>
<p>Roses are <?=$color?></p>
</body>
</html>

19
Output Operations
Using Quotes in the echo and print.
 Be careful when using HTML code or any other string
that includes quotes!
 echo and print use quotes to define the beginning and
end of the string.
 Therefore, if the string contains quotations:
 Don't use quotes inside the string
 Escape the quotes that are within the string with a
backslash - place a backslash directly before the quotation
mark ( \“)
 Use single quotes (apostrophes) for quotes inside the
string.
20
Output Operations
Using Quotes in the echo and print. (Cont.)
 Example:
<?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 ‘ (single quote)
echo "<h5 class = 'specialH5'>I love using PHP!</h5>";
?>
 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 the quotation is to be used within the
string and NOT to be used to delimit (mark) the string.

21
Output Operations
Formatting Output
 To format the output PHP provides two functions printf() and sprintf() (to be
used with echo and print).
 The printf() function is used to format the displayed data.
 Syntax:
printf(output_format, param1, param2, … )
- where, the param1, param2, …, is the output value to be formatted, can
be in form of expression or variable.
- each of output_format is a format code for the param1, param2, … in the
form of a percentage symbol (%), followed by a field width, and a type
specifier.
- the field width is an integer literal (for integers formatting) or two integer
literals separated by a decimal point (for floats/doubles formatting)
- the most common type specifiers are: s – for string, d – for integers, and
f – for floats & doubles, e – for exponential notation of doubles.

22
Output Operations
Formatting Output (Cont.)
 Examples of output_format:
%12s – a string field of 12 characters
%5d – an integer field of 5 digits
%3.2f – a float/double field of 6 spaces, with two digits to the
right of the decimal point, the decimal point, and three
digits to the left.

23
Output Operations
Formatting Output (Cont.)
 printf() allows padding out an argument value to a fixed width.
 Any character can be used for the padding, either to the left or the
right of the value.
 Padding is useful for adding leading zeroes to numbers, and for right-
aligning strings.
 To add padding, insert a padding specifier between the '%' character
and the type specifier.
 A padding specifier takes the format: <padding character><width>
 <padding character> can be a zero or a space. If not specified,
spaces are used.
 To use a different character, write an apostrophe (') followed by the
character to use.
 <width> is the number of characters to pad the value out to. A
positive number adds padding to the left; a negative number adds
24
padding to the right.
Output Operations
Formatting Output (Cont.)
 Examples:

25
Output Operations
Formatting Output (Cont.)
 The sprintf() function is identical to printf(), except that rather than
directly outputting the result, it returns the value so that you can store
it in a variable (or otherwise manipulate it).
 This is useful if you want to process the result before displaying it, or
store it in a database.
 sprintf() uses the same syntax as printf().
 Example:

Output:

26
Output Operations
Formatting Output (Cont.)
 The number_format() function formats a number with grouped
thousands with comma (,) as the thousands separator.
 Syntax
number_format(number,[decimals,decimalpoint,separator])
- number is required, is the value to be formatted. If no other parameters are
set, the number will be formatted without decimals
- decimals is optional, to specify how many decimals with a dot (.) as decimal
point.
- decimalpoint is optional, to specify what string to use for decimal point.
- separator is optional, to specify the character to use for thousands
separator. If this parameter is given, all other parameters are required as
well.

• Note: This function supports one, two, or four parameters (not


three).
27
Output Operations
Formatting Output (Cont.)
 Example:

echo number_format(“2500000");
echo "<br />";
echo number_format(“2500000",2);

- the output of the code above will be:

25,000,000
25,000,000.00

28
String Manipulations
Concatenation
 Concatenation is joining two ore more strings, which
can be performed using the dot notation.
 Example:

<?php
$txt1 = "Hello there, World!";
$txt2 = “Have a nice day!";
$greet = $txt1 . " " . $txt2
echo $greet;
?>

29
String Manipulations
Using the strlen() function
 The strlen() function is used to return the length (number of
characters) of a string.
 It is used in the form: strlen(string)
 Example:
<?php
echo strlen("Hello world!");
?>
 This will display:
12
 The length of a string is often used in loops or other functions,
when it is important to know when the string ends. (i.e. in a loop,
we would want to stop the loop after the last character in the
string). 30
String Manipulations
Using the strpos() function
 The strpos() function is used to search for the position of the first
character of a substring in a long string.
 It is used in the form: strpos(string, substring )
 If a match is found, it will return the position of the first matched
character. Otherwise, it will return a false.
 To find the position of string "world" in a string:
<?php
echo strpos("Hello world!","world");
?>
 The output will be: 6
 The position of the string "world" in the string is position 6,
because the first position in the string is always 0, and not 1.
31
Expressions and Operators
Arithmetic Expression and Operators
 An expression such as “a + b” is an arithmetic expression which
evaluates to a numeric value.
 The expression contains operands and one or more arithmetic
operators.
 The following lists PHP arithmetic operators:

+ Addition Add two values


̶ Subtraction Subtract the second value from the first
* Multiplication Multiply two values
/ Division Divide the first value by the second
Divide the first value by the second and
% Modulus return only the remainder
(for example, 7 % 5 yields 2)

32
Expressions and Operators
Assignment Operation and Operators
•Assigning value to a variable is called assignment operation.
•The operation is performed by an assignment statement of the
following form:

$variable = expression;
- expression can be a value (numeric or string), arithmetic
expression, a
variable, or a function call.
•For example, $a = 5; assigns the value 5 to $a.
•This assignment can be combined with some other operators like:
$a += 2;
- if $a already had a value of 5, then after this statement it would be 7,
which is equivalent to:
$a = $a + 2; 33
Expressions and Operators
Assignment Operation and Operators (Cont.)

•For the following combined assignment statement:

$a *= $b + 5;

it is equivalent to

$a = $a * ($b + 5);

because $a is to be multiplied by the whole expression on the right of


equal sign which is $b + 5.

•Other variations include: += -= *= /= %=

34
Expressions and Operators
Increment and Decrement Operators

•For the following combined assignment statements:

$a += 1; or $a -= 1; - to add or subtract 1 to or from $a

•PHP provides the increment and decrement operators, respectively.


•They are listed as follows:

Adds 1 to the value before processing the


++value Pre-Increment
expression which uses the value
Subtracts 1 from the value before processing the
--value Pre-Decrement
expression which uses the value
Adds 1 to the value after processing the
value++ Post-Increment
expression which uses the value
Subtracts 1 from the value after processing the
value-- Post-Decrement
expression which uses the value
35
Expressions and Operators
Boolean/Logical Expressions and Operators
•A Boolean/logical expression is a comparison expression
that evaluates to either true or false.
•Examples:
$x < 5
$a >= $b - $c
•The comparison operator is an operator used to
compare two operands for equality or inequality in a
Boolean/logical expression.
•The logical operator is an operator that compares two or
more Boolean/logical expressions.
36
Expressions and Operators
Boolean/Logical Expressions and Operators
•The comparison operators are listed in the following table:

== Equal Checks for equal values


= = = Identical Checks for equal values and data types
!= Not Equal Checks for values not equal
Checks for values not equal or not the same
!== Not Identical
data type
Checks for one value being less than the
< Less than
second
Checks for one value being greater than the
> Greater than
second
Less than or Equal Checks for on value being less than or equal
<=
to to the second
Greater than or Checks for on value being greater than or
>=
Equal to equal to the second
37
Expressions and Operators
Boolean/Logical Expressions and Operators

•The logical operators are listed in the following table:

And Checks if two or more statements are true

&& Same as And

Or Checks if at least one of two statements is true

|| Same as Or

Xor Checks if only one of two statements is true

! Checks if a statement is not true

38
Operator Precedence and Associativity
• For the following operation:
$a = 7 - 4 + 1;
• If the minus happens before the plus, the result would be
4. If the plus happens first, the result is 2.
• An order of precedence was established, along with
associativity.
• The order of precedence establishes a “priority" for
operators, where those with the highest rank will be
evaluated first.
• When there are several operators of the same rank, they
will be processed from left to right if they are left
associative, and right to left if they are right associative.
39
Operator Precedence and Associativity
• Some operators, such as the comparison operators, have neither left
nor right associativity.
• The increment and decrement operators ( ++ and -- ) are right
associative, while the others are left associative.
• The order of precedence and associativity are summarized as follows:
() left to right
functions/methods left to right
unary - -- ++ ! right to left
/ * % left to right
+ - left to right
< > <= >= left to right
== != === !== left to right
&& left to right
|| left to right
And left to right
Xor left to right
Or left to right
40
Operator Precedence and Associativity
• Wrapping part of an expression in parentheses can override
the order of precedence.
• The innermost parentheses are processed first with the
outermost last.
• For example:
(7 - 4) + 1 will give a result of 4
7 - (4 + 1) will give a result of 2
2+3*3 will give a result of 11
2 + (3 * 3) will also give 11
(2 + 3) * 3 will give a result of 15
1+3+3*2 will give a result of 10
1 + ((3 + 3) * 2) will give a result of 13
(1 + (3 + 3)) * 2 will give a result of 14
• Parentheses are essential to create a complex expression so
that it is easier to see the process of evaluation. 41
Decision/Selection Control
 The decision or selection control structure allows you to control
Structures
the behavior of program execution.
 It enables you to specify the circumstances under which code will
be executed, generally based on conditions.
 PHP provides the following statements for decision or selection
control structures:
1) The if Statements:
if - to execute some code only if a specified condition is
true
if...else - to execute some code if a condition is true and
another code if the condition is false
if...elseif....else - to select one of several blocks of code to
be executed
2) The switch Statement - to select one of many blocks of code
to be executed
42
The if Statements
 Syntax of the if statement:

if (condition) {
statement;
}

 Syntax of the if…else statement:

if (condition) {
statement;
}
else {
statement;
} 43
The if Statements
 The syntax of the if…elseif … else statement:

if (condition) {
statement;
}
elseif (condition) {
statement;
}
elseif (condition) {
statement;
}

else {
statement;
}

• Each of the condition is a Boolean/logical expression and


statement is any PHP executable statement 44
The if Statements
• Examples:
1)
if ($x < 0) {
echo “$x is negative.”;
}
2)
$finished = true;
$pgs_completed = 50;
if ( ($pgs_completed >= 50) || $finished)) {
echo "Hey you're done, get some sleep!<br>";
}
else {
echo "You're not done yet - no sleep tonight!<br>";
} 45
The if Statements
• More example:

$temp = 25;
if ($temp > $idealtemp) {
print "Add cold water“;
}
elseif ($temp < $idealtemp) {
print "Add hot water“;
}
else {
print "Add more water“;
}

46
The switch Statement
 Syntax:
The single expression n (most
switch (n) { often a variable), is evaluated.
case label1: The value of the expression is
statement(s); then compared with the values
break; for each case in the structure.
case label2: If there is a match, the
statement(s); statement(s) associated with
break; that case is executed until it
…… encounters the break statement.
case labeln: The break is used to prevent the
statement(s); code from running into the next
break; case automatically.
default: The default statement is used if
statement(s); no match is found
}
47
The switch Statement
 Example:
switch ($x) {
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo “Number is not in the range.";
} 48
Repetition/Iteration Control Structures
 Repetition or iteration control structures are also known as loops.
 Loops execute a block of code a specified number of times, or
while a specified condition is true.
 Often, you want the same block of code to run over and over
again in a row.
 Instead of adding several almost equal lines in a script we can use
loops to perform a task like this.
 PHP provides the following looping statements :
while - loops through a block of code while a specified condition is
true
do...while - loops through a block of code once, and then repeats
the loop as long as a specified 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 49
The while Loop
 Syntax
while (condition) {
statement(s);
}
 While the condition is true, the statement(s) will be
executed. Once the condition is false the loop exits.
 Example:
$n = 1;
while($n <= 5) {
echo "The number is " . $n . "<br />";
$n++;
}

50
The while Loop
 More example:

$count = 1;
while ($count <= 10) {
if ( ($count % 3) == 0) {
echo "$count is divisible by 3!<br>";
}
$count++;
}

51
The do…while Loop
 Syntax:
do {
statement(s);
}
while (condition);
 The loop will always execute statement(s) once, it will then check
the condition, and repeat the loop while the condition is still true.
The loop exits once the condition is false.
 Example:
$n = 1;
do {
echo "The number is " . $n . "<br />";
$n++;
}
while($n <= 5);
52
The do…while Loop
 More example:

$count = 1;
do {
if ( ($count % 3) == 0) {
echo "$count is divisible by 3!<br>";
}
$count++;
}
while ($count <= 10);

53
The for loop
 The for loop is used when you know in advance how many times
the script should run.
 Syntax:

for (initial; condition; increment) {


statement(s);
}
 initial: Mostly used to set a counter variable (but can be any code to
be executed once at the beginning of the loop)
 condition: Evaluated for each loop iteration. If it is true, the loop
continues. If it is false, the loop ends.
 increment: Mostly used to increment a counter variable (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).

54
The for loop
 Examples:
1)
for ($n = 1; $n <= 5; $n++) {
echo "The number is " . $n . "<br />";
}

2)
for ($count = 1; $count <= 10; $count++) {
if ( ($count % 3) == 0) {
echo "$count is divisible by 3!<BR>";
}
}
55
User-defined Functions
 User-defined function is a function that is created by the
programmer.
 It contains a block of PHP code that can be executed once or
many times.
 To keep the browser from executing a script when the page loads,
put the script into a user-defined function.
 A function will be executed by a call to the function. A function can
be called from anywhere within a page.
 The function must first be defined before use, by using the
function keyword followed by a given name, followed by
parentheses with optional parameter(s) in it.
 Code for the function is placed in between the braces after the
function header, as follows:
function function_name ([parameter_list]) {
statement(s);
}

56
User-defined Functions
 A parameter_list is one or more data placed within the
parentheses at the function header.
 Some functions do not have parameters, therefore
empty parentheses are placed after the identifier.
 The function_name given following the rules of giving a
variable name except that it does not start with the dollar
sign.
 The name is case insensitive. The function name is
given to reflect what the function does.
 To call a function is simply by using the function name
followed by parentheses, as follows:
function_name();

57
User-defined Functions
 Example – a function that displays a message:

Function
definition

Output:
Function call

58
User-defined Functions
A Function with Parameters
• Parameters are used to add more functionality to a function. A
parameter is like a variable.
• Parameters are specified after the function name, inside the
parentheses.
• When the function is called, the argument must be added inside the
parentheses at the function call.
• This is to pass the value from the argument to the function
parameter.
• They are used in the following form:
function_name (param1, param2, …) {
...
}
…..
function_name(arg1, arg2, …); 59
User-defined Functions
 The number of parameters at the function header must
agree with the number of arguments at the function call.
 Example:

Output:

60
User-defined Functions
A Function that Returns a Value
 To let a function return a value, the function
must have the return statement.
 The function call must be assigned to a variable
or displayed directly in an input operation.
 Example:

Output:
61
User-defined Functions
Pass by Value and Pass by Reference
 Pass by value means that the function call will pass
the values from the arguments to the function
parameters.
 Example:

Output:

62
User-defined Functions
Pass by Value and Pass by Reference (Cont.)
 Pass by reference means that the function call will pass the
address along with the values of the arguments to the function
parameters.
 For the parameters to receive the address of the arguments the
ampersand symbol (&) is placed before the parameter name.
 Example:

Output:

63
User-defined Functions
Setting Default Values for Function Parameters
 A parameter can be set to have a default value if the function call
doesn't pass any argument.
 For example, the following function prints NULL in case there is no
value passed to the parameter of this function.
<?php
function printMe($param = NULL) {
print $param;
}
printMe("This is test");
printMe();
?>
- this will produce following result:
This is test

64
Variable Scope
 Every variable has the scope in which part of script it resides.
 a variable is accessible anywhere within a script once it had
been defined.
 Variable defined within a function has its own scope
 variables defined within a function are not available outside of it
 variables defined outside of a function are not available within
the function.
 To alter variable scope within a function, use the global statement,
for example:
function function_name() {
global $var;
}
$var = value;

65
Variable Scope
• Example – using global variable:

Output:

66
Static Variable
 Static variables do not get destroyed when the function
terminates.
 To create a static variable within a function, use the
static statement, as follows:
static $var = value;
 Example:

Output:

67

You might also like