2 - PHP 1 PDF
2 - PHP 1 PDF
2
Using Variables and Constants
The values stored in computer memory are called variables
The values, or data, contained in variables are classified into
categories known as data types
The name you assign to a variable is called an identifier and it
must begin with a dollar sign ($)
can include letters (A to Z, a to z) and numbers (0 to 9) or an underscore
(_) … but cannot start with a number
cannot include spaces
is case sensitive (are $firstName and $FirstName referring to the same
variable?)
should follow a consistent variable naming style (either $votingAge or
$voting_age or …)
3
Declaring, Initialising and Modifying Variables
Specifying and creating a variable name is called
declaring the variable
Assigning a first value to a variable is called initialising
the variable
In PHP, you must declare and initialise a variable in the
same statement:
$variable_name = value;
4
Displaying the Values of Variables
To print the value of a variable, pass the variable name to the echo
statement without enclosing it in quotation marks:
echo $votingAge;
To print both text strings and variables, send them to the echo
statement as individual arguments, separated by commas:
echo "<p>The legal voting age is ",
$votingAge, ".</p>";
Alternatively, by double/single quotation marks
echo "<p>The legal voting age is
$votingAge.</p>";
Note, single quotation marks behave differently
echo '<p>The legal voting age is
$votingAge.</p>';
Text ‘$votingAge’ itself will be printed out.
5
An example
<!DOCTYPE html> Hello world!
<html>
<body>
5
10.5
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br />";
echo $x;
echo "<br />";
echo $y;
?>
</body>
6
</html>
Defining Constants
A constant contains information that does not change during the
course of program execution
Constant names use all uppercase letters
You should follow a consistent constant naming style
PASSING_MARK or PASSINGMARK
8
Working with Data Types
A data type is the specific category of information that a variable
contains
Data types that can be assigned only a single value are called
primitive types
9
Working with Data Types (continued)
Strongly typed programming languages require you
to declare the data types of variables
Static or strong typing refers to data types that do not
change after they have been declared
C is a strongly typed programming language
10
Numeric Data Types
PHP supports two numeric data types:
An integer is a positive or negative number with no
decimal places (-250, 2, 100, 10,000)
A floating-point number is a number that contains
decimal places or that is written in exponential notation
(-6.16, 3.17, 2.7541)
Exponential notation, or scientific notation, is short for
writing very large numbers or numbers with many decimal
places (2.0e11)
11
Boolean Values
A Boolean value is a value of true or false
It decides which part of a program should execute and which
part should compare data
In PHP programming, you can only use true or false
In other programming languages, you can use integers such as
1 = true, 0 = false
12
Working with Data Types (continued)
The data type of a variable (identifiers) or constant
depends on the data type of the value assigned to it
$unitName = “Web Programming”;
$lectureHours = 2; Hint: Give meaningful names
$creditPoints = 12.5; Did you notice any naming pattern?
$isCoreUnit = TRUE;
13
Working with Data Types (continued)
The PHP language supports:
A resource data type – a special variable that holds a reference to
an external resource such as
a database or XML file
Reference or composite data types, which contain multiple values
or complex types of information
Two reference data types: arrays and objects
14
Arrays
An array contains a set of data represented by a single variable name
16
Accessing/Modifying Element Information
Accessing an element
echo "Canada's largest province is
$provinces[4].</p>";
Use the count() function to find the total number
of elements in an array
echo "<p>Canada has ",
count($provinces), " provinces.</p>";
Modifying an element
$provinces[9] = "BC";
17
print_r() Function
Use to print or return information about variables
Most useful with arrays because they print the index and
value of each element
18
Building Expressions
An expression is a combination of operands and
operators that are interpreted according to the
particular rules of precedence and can be evaluated
by the PHP scripting engine to produce a result
Operands are literals, constants, variables, and
functions
A literal is a value such as a literal string or a number
Operators are symbols (e.g. +, *) that are used in
expressions to manipulate operands
19
Building Expressions (continued)
PHP Operator Types
22
Prefix Operator vs. Postfix Operator
Prefix increment operator
$ticketNum = 100;
$nextTicketNum = ++$ticketNum; // assigns 101
$nextTicketNum = ++$ticketNum; // assigns 102
23
Assignment Operators
Assignment operators are used for assigning a value to a
variable:
$myFavoriteSuperHero = "Superman";
$myFavoriteSuperHero = "Batman";
Compound assignment operators perform mathematical
calculations on variables and literal values in an expression, and
then assign a new value to the left operand
$x += $y; same as $x = $x + $y;
$x *= $y; same as $x = $x * $y;
24
Assignment Operators (continued)
PHP assignment operators
25
Comparison Operators
Comparison operators are used to compare two
operands and determine how one operand compares to
another
A Boolean value of true or false is returned after two
operands are compared
The comparison operator compares values, whereas the
assignment operator assigns values
Comparison operators are used with conditional
statements and looping statements
26
Comparison Operators (continued)
PHP comparison operators
27
Comparison Operators (continued)
$x = 100;
$y = "100";
28
Conditional Operators
The conditional operator executes one of two expressions,
based on the results of a conditional expression
The syntax for the conditional operator is:
conditional expression
? expression1 : expression2;
29
Logical Operators
Logical operators are used for comparing two Boolean
operands for equality
A Boolean value of true or false is returned after two
operands are compared
PHP logical operators
30
Special Operators
PHP special operators
32
gettype() function
Returns one of the following strings, depending on the data type
– no guessing needed:
Boolean
Integer e.g.
Double $num = 1;
String echo gettype($num);
Array
Would echo out the type:
Object
integer
Resource
NULL
Unknown type
33
The var_dump() function
Returns the data type and value
e.g.
$num = 1;
var_dump($num);
Output:
int(1)
34
Defining Functions
Functions are groups of statements that you can execute as a
single unit
Function definitions are the lines of code that make up a function
<?php
function name_of_function(parameters) {
statements;
}
?>
A parameter is a variable that is used within a function
Parameters are placed within the parentheses that follow the
function name. Functions do not have to contain parameters
The set of curly braces (called function braces) contain the
function statements, which do the actual work of the function
35
Defining and Calling Functions
simplephp example in Week 1
function concatenate1($str1, $str2) {
echo $str1." : ".$str2;
}
concatenate1($name, $pwd);
36
Understanding Variable Scope
Variable scope is ‘where in your program’ a declared
variable can be used
A variable’s scope can be either global or local
A global variable is one that is declared outside a
function and is available to all parts of your program
A local variable is declared inside a function and is only
available within the function in which it is declared
37
Understanding Variable Scope (Cont.)
<?php
// all functions usually grouped together
// in one location
function testScope() {
$localVariable = "<p>Local variable</p>";
echo "<p>$localVariable</p>";
// prints successfully
}
$globalVariable = "Global variable";
testScope();
echo "<p>$globalVariable</p>";
echo "<p>$localVariable</p>"; // error message
?>
38
The global Keyword
With many programming languages, global variables are
automatically available to all parts of your program including
functions.
In PHP however, we need to use the global keyword to
declare a global variable in a function where you would like to
use it.
<?php
function testScope() {
global $globalVariable;
echo "<p>$globalVariable</p>";
}
$globalVariable = "Global variable";
testScope();
?>
If no “global” above, an error message will be printed out. 39
Using Autoglobals
PHP includes various predefined global arrays, called
autoglobals or superglobals
Autoglobals contain client, server, and environment
information that you can use in your scripts
Autoglobals are associative arrays – arrays whose
elements are referred to with an alphanumeric key
instead of an index number
Array Description
$GLOBALS An array of references to all variables that are defined with global scope
$_GET An array of values from the submitted form with the GET method
$_POST An array of values from the submitted form with the POST method
$_COOKIE An array of values passed to HTTP cookies
$_SESSION An array of session variables that are available to the current script
$_SERVER An array of information about this script's web server
$_FILES An array of information about uploaded files
$_ENV An array of environment information
$_REQUEST An array of all the elements found in the $_COOKIE, $_GET, and $_POST array
41
Using Autoglobals (continued)
Use the global keyword to declare a global variable within the
scope of a function
Use the $GLOBALS autoglobal to refer to the global version of
a variable from inside a function
$_GET is the default method for submitting a form
$_GET and $_POST allow you to access the values of forms
that are submitted to a PHP script
$_GET appends form data as one long string to the URL
specified by the action attribute
$_POST sends form data as a transmission separate from the
URL specified by the action attribute
42
Using Autoglobals (continued)
echo "This script was executed with the following
server software: ", $_SERVER["SERVER_SOFTWARE"],
"<br />";
echo "This script was executed with the following
server protocol: ", $_SERVER["SERVER_PROTOCOL"],
"<br />";
echo $_GET["name"];
echo $_GET["address"];
echo $_POST["name"];
echo $_POST["address"];
43
Making Decisions
Decision making or flow control is the process of
determining the order in which statements execute in a
program
The special types of PHP statements used for making
decisions are called decision-making statements or
decision-making structures
There are three types of decision-making statements
if statement
if...else statement
switch statement
44
if Statement
Used to execute specific programming code if the
evaluation of a conditional expression returns a value of
true
if (conditional expression)
statement; // or {statements}
example
$exampleVar = 5;
if ($exampleVar == 5) { // Condition evaluates to'TRUE'
echo "<p>The condition evaluates to true.</p>";
echo '<p>$exampleVar is equal to ',
"$exampleVar.</p>";
echo "<p>Each of these lines will be printed.</p>";
}
echo "<p>This statement always executes after if.</p>";
45
if...else Statement
An if statement that includes an else clause. The else
clause executes when the condition in an if...else
statement evaluates to false
if (conditional expression)
statement; // or {statements}
else
statement; // or {statements}
Example
$today = "Tuesday";
if ($today == "Monday")
echo "<p>Today is Monday</p>";
else
echo "<p>Today is not Monday</p>";
47
switch Statement
Controls program flow by executing a specific set of statements
depending on the value of an expression
Compares the value of an expression to a value contained within a
special statement called a case label
A case label is a specific value that contains one or more statements
that execute if the value of the case label matches the value of the
switch statement’s expression
switch (expression) {
case label:
statement(s);
break;
case label:
statement(s);
break;
...
default:
statement(s);
}
48
switch Statement (continued)
A case label consists of:
The keyword case
A literal value or variable name (e.g. “Boston”, 75, $Var)
A colon
A case label can be followed by a single statement or multiple
statements
Multiple statements for a case label do not need to be enclosed
within a command block
The default label contains statements that execute when the
value returned by the switch statement expression does not
match a case label
49
Example – What Should I Do Today?
50
Your Agenda is …
51
Implement the Interface?
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head> <title>An example of using "Switch"</title></head>
<body>
<H1>An example of using "Switch" in PHP</H1>
<form> Please select a weekday:
<select name="weekday" >
<option value="Sunday">Sunday</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
<option value="Friday">Friday</option>
<option value="Saturday">Saturday</option>
</select> <br/><br/>
Select your role:
<input type="radio" name="role" value="teacher">teacher
<input type="radio" name="role" value="student">student
<br/><br/>
<input type="submit" value="Submit" />
</form>
<p> Your agenda is shown as below.</p>
</body> 52
Deliver the Agenda
<?php
if(isset($_GET['weekday']) && isset($_GET['role'])){
$weekday = $_GET['weekday']; $role =$_GET['role'];
echo "As a $role, on $weekday, your agenda is: ";
if($role == 'student'){ // a student's agenda
switch($weekday) {
case 'Monday': echo 'HIT3324 Lecture & Lab'; break;
case 'Wednesday': echo 'HIT3324 Lab'; break;
default: echo 'Study harder';
} // end of switch
}
else { // a teacher's agenda
switch($weekday) {
case 'Monday': echo 'HIT3324 Lecture & Lab'; break;
case 'Wednesday': echo 'HIT3324 Lab'; break;
case 'Tuesday':
case 'Thursday':
case 'Friday': echo 'Research'; break;
default: echo 'Have a rest';
} // end of switch
} // end of inner if
} // end of outer if
?> 53
</HTML>
Repeating Code
A loop statement is a control structure that repeatedly
executes a statement or a series of statements while a
specific condition is true or until a specific condition
becomes true
There are four types of loop statements:
while statements
do...while statements
for statements
foreach statements
54
while Statement
Repeats a statement or a series of statements as long as a given
conditional expression evaluates to true
while (conditional expression) {
statement(s);
}
55
Counter in while Statement
Using an increment operator
$count = 1;
while ($count <= 5) {
echo "$count<br />";
$count++;
} // print 1,2,3,4,5 in 5 lines
Using a decrement operator
$count = 10;
while ($count > 0) {
echo "$count<br />";
$count--;
} // print 10,9,8,7,6,5,4,3,2,1 in 10 lines
Using the assignment operator *=
$count = 1;
while ($count <= 100) {
echo "$count<br />";
$count *= 2;
} // print 1,2,4,8,16,32,64 in 7 lines
56
Be Careful with Infinite Loop
In an infinite loop, a loop statement never ends because its
conditional expression is never false
$count = 1;
while ($count <= 10) {
echo "The number is $count";
}
example
$daysOfWeek = array("Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday");
$count = 0;
do {
echo $daysOfWeek[$count], "<br />";
$count++;
} while ($count < 7); // print “Monday” to “Sunday” in 7 lines
59
for Statement
Used for repeating a statement or a series of statements as long
as a given conditional expression evaluates to true
Can also include code that initialises a counter and changes its
value with each iteration
for (counter declaration and initialisation;
condition; update statement) {
statement(s);
}
Example
$fastFoods = array("pizza", "burgers", "french fries",
"tacos", "fried chicken");
for ($count = 0; $count < 5; $count++) {
echo $fastFoods[$count], "<br />";
} // print “pizza” to “fried chicken” in 5 lines
60
foreach Statement
Used to iterate or loop through the elements in an array
Does not require a counter; instead, you specify an array
expression within the pair of parentheses following the
foreach keyword
foreach ($array_name as $variable_name) {
statements;
}
example
$daysOfWeek = array("Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday");
foreach ($daysOfWeek as $day) {
echo "<p>$day</p>";
}
61
Example – Factorial and Fibonacci
62
Factorial
63
Fibonacci
64
Working on Factorial
function factorial($number)
{
if($number > 170)
return 0; // this function can only calculate
// the factorial of a number below 171
$i = 1;
$result =1;
while ($i <= $number){
$result = $result * $i;
$i++;
}
return $result;
}
65
Working on Fibonacci
function fibonacci($number)
{
$first = 0; $second = 1;
if($number >= 2) {
echo "The first $number fibonacci number are: <br/>";
echo $first.'<br/>';
echo $second.'<br/>';
for($i=1; $i<=$number-2; $i++){
$temp = $first + $second;
$first = $second;
$second = $temp;
echo $temp.'<br/>';
}
}
elseif ($number==1)
echo "The first fibonacci number is 0: <br/>";
else
echo 'Wrong input number';
}
66