You are on page 1of 39

Introduction to PHP – Part.

1
Chapter 9 from text book

1
Outline
 Server-Side Basics
 PHP Basic Syntax
◦ Data Types
◦ Control Structures
◦ Arrays
 Embedded PHP
 Advanced PHP Syntax
◦ Functions
◦ Variable Scope
2
Do you want to build a website like:

http://builtwith.com
3
Server-Side Basics
Three-Tier

Presentation Database
Browser Logic Tier
Tier

Web Server

 some URLs actually specify programs that the web


server should run, and then send their output back to
you as the result:
◦ http://www.ksu.edu.sa/Pages/default.aspx
◦ the above URL tells the server ksu.edu.sa to run the program
default.aspx and send back its output
4
Server-Side Web Programming
 Server-side pages are programs written using
one of many web programming languages/
frameworks
◦ examples: PHP, Java/JSP, Ruby on Rails, ASP.NET,
Python, Perl

 The web server contains software that


allows it to run those programs and send
back their output as responses to web
requests
5
What is PHP?
 PHP stands for "PHP Hypertext
Preprocessor"
 A server-side scripting language
 Used to make web pages dynamic:
◦ Provide different content depending on context
◦ Interface with other services: database, e-mail, etc
◦ Authenticate users
◦ Process form information
 PHP code can be embedded in XHTML
code

6
Lifecycle of a PHP web request

•Browser requests a .html file (static content): server just sends that file
•Browser requests a .php file (dynamic content): server reads it, runs
any script code inside it, then sends result across the network
-script produces output that becomes the response sent back
7
Hello, World!
The following contents could go into a file hello.php: 
<?php
print "Hello, world!";
?>

Hello, world!

• A block or file of PHP code begins with <?php and ends with ?>
• PHP statements, function declarations, etc. appear between these
endpoints

8
Viewing PHP output
 You can't view your .php page on your local hard drive; you'll either see
nothing or see the PHP source code
 if you upload the file to a PHP-enabled web server, requesting the .php
file will run the program and send you back its output

9
PHP Syntax Template
HTML content
<?php
PHP code
?>
HTML content
<?php
PHP code
?>
HTML content ...
• Any contents of a .php file between <?php and ?> are
executed as PHP code
• All other contents are output as pure HTML
• PHP statements are terminated with semicolons
10
Console Output: print
• Syntax: print “text”;
print "Hello, World!\n";
print "Escape \"chars\" are the SAME as
in Java!\n";
print "You can have line breaks in a
string.";
Hello, World! Escape "chars" are the SAME as in Java! You can have line
breaks in a string.

• Some PHP programmers use the equivalent


echo instead of print
11
Comments
// single-line comment
# single-line comment

/*
multi-line comment
*/

12
Variables
 Syntax: $name = expression;
$user_name = “Amal Ahmad";
$age = 13;
$College_age= $age + 5;
$this_class_is_useful= TRUE;
• Names are case sensitive; keywords and function names are not
case sensitive.
• Names always begin with $, on both declaration and usage
• Always implicitly declared by assignment (type is not written)
• A loosely typed language (like JavaScript)
• A variable that has not been assigned a value is unbound and has
the value NULL
•IsSet($x) function, checks if the variable $x is set to a value or
not. 13
Types
 Basic types: int, float, boolean, string, array, object, NULL
 Type can be determined with the gettype function and
with the is_int function and similar functions for
other types
 Type conversions can be forced in three ways
◦ (int)$sum
◦ intval($sum) using several conversion functions
◦ settype($x, “integer”)

14
Types
 Implicit type conversions as demanded by the
context in which an expression appears
◦ A string is converted to an integer if a
numeric value is required and the string starts
with a digit or a sign.
◦ A string is converted to a double if a numeric
value is required and the string is a valid
double literal (including either a period or e
or E)

15
String Type
$favorite_color= “Black";
print $favorite_color[2]; // a
• Zero-based indexing using bracket notation
• There is no char type; each letter is itself a String
• String concatenation operator is . (period), not+
- 5 + "2 nice books" === 7
- 5 . "2 nice books " === "52 nice books "
• Can be specified with " " or ' '

16
Interpreted strings
$age = 16;
print "You are " . $age . " years old.\n";
print "You are $age years old.\n";
//You are 16 years old.

• Strings inside " " are interpreted


- variables that appear inside them will have their values
inserted into the string
• Strings inside ' ' are not interpreted:

print 'You are $age years old.\n';


//You are $age years old.\n

17
String functions

18
bool (Boolean) Type
$feels_like_summer = TRUE;
$php_is_bad = FALSE;
$student_count = 217;
$nonzero = (bool) $student_count; // TRUE

• The following values are considered to be FALSE (all others


are TRUE):
- 0 and 0.0 (but NOT 0.00 or 0.000)
- "", "0", and NULL (includes unset variables)
- Arrays with 0 elements
• Can cast to booleanusing (bool)
• FALSE prints as an empty string (no output); TRUE prints as 1
• TRUE and FALSE keywords are case insensitive

19
int and float Types
$a = 7 / 2; // float: 3.5
$b = (int) $a; // int: 3
$c = round($a); // float: 4.0
$d = "123"; // string: "123"
$e = (int) $d; // int: 123

•Int for integers and float for reals


• Division between two int values can produce a float

20
Math operations

the syntax for method calls, parameters,


returns is the same as Java

21
Relational Operators
 PHP has the usual comparison operators: >, <<=, >=,
== and !=
 PHP also has the identity operator ===
◦ This operator does not force coercion
 The regular comparisons will force conversion of
values as needed
◦ Comparing a string with a number (other than with ===)
will result in the string converting to a number if it can be.
Otherwise the number is converted to a string
◦ If two strings are compared (other than with ===) and the
strings can both be converted to numeric values, the
conversion will be done and the converted values
compared
◦ Use strcmp on the strings if the latter feature is a
problem

22
Boolean Operators
 PHP supports &&, || and ! as in
C/C++/Java
 The lower precedence version and and
or are provided
 The xor operator is also provided

23
if/else Statement
if (condition) {
statements;
} elseif(condition) {
statements;
} else {
statements;
}

NOTE: although elseif keyword is much more common,


else if is also supported

24
for loop (same as Java)

for (initialization; condition; update) {


statements;
}

for ($i = 0; $i < 10; $i++) {


print "$i squared is " . $i * $i . ".\n";
}

25
while loop (same as Java)
while (condition) {
statements;
}

do {
statements;
} while (condition);

break and continue keywords also behave as in


Java

26
Arrays
 Arrays in PHP combine the characteristics
of regular arrays and hashes
◦ An array can have elements indexed numerically.
These are maintained in order
◦ An array, even the same array, can have elements
indexed by string. These are not maintained in
any particular order
 The elements of an array are, conceptually,
key/value pairs

27
Array Creation
 Two ways of creating an array
◦ $a = array(); // empty array (length 0)
◦ Assigning a value to an element of an array,
e.g. $a[0]=7; // one element
 Create a numerically indexed array
◦ $list =array(23, „xiv‟, “bob”, 777);
 Create an array with string indexes
◦ $a = array(“a” =>“apple”, “o” =>“orange”)
 Array elements are accessed by using a subscript in
square brackets.
 To append, use bracket notation without specifying an
index
$a2 = array("some", "strings", "in", "an", "array");
$a2[] = "Ooh!"; // add string to end (at index 5)

28
Array functions

29
Functions for Dealing with Arrays
$cites = array(“Makkah”, “Madeena”, “Riyadh”,
”Khubar”);
unset($cites[2]); // removes “Riyadh”
$x = array_keys($cities); // returns 0,1,3
$y = array_values($cities); // returns Makkah,
Madeena, Khubar
array_key_exists(2, $cites); //returns false

$words = explode(“ ”,“This is a string”); // returns


an
array consists of 4 elements “This”, “is”, “a”,
“string”
$str = implode(“ ”, $cites ); // returns a string
“MakkahMadeenaKhubar”

30
Sequential Access to Array
Elements
 PHP maintains a marker in each array, called the current
pointer
◦ Several functions in PHP manipulate the current pointer
◦ The pointer starts at the first element when the array is created
 The next function moves the pointer to the next
element and returns the value there
$cites = array(“Makkah”, “Madeena”, “Riyadh”,
”Khubar”);
$city = current($cities);
print (“$city - ”);
While ($city = next($cities))
print (“$city - ”);

Makkah - Madeena - Riyadh – Khubar-

31
Sequential Access to Array Elements
 The each function move the pointer to the next
element and returns the key/value pair at the previous
position
◦ The key and value can be accessed using the keys “key” and
“value” on the key/value pair
$cites = array(“Makkah” => 45, “Madeena” => 48,
“Riyadh” => 50, ”Khubar” => 43);
While ($city = each($cities)){
$name = $city[“key”];
$temp = $city[“value”]
print (“The temperature of $city is $temp <br />”);
}

The temperature of Makkah is 45


The temperature of Madeena is 48
The temperature of Riyadh is 50
The temperature of Khubar is 43
32
Sequential Access to Array Elements
 next and currentfunctions return false if
no more elements are available
 prev moves the pointer back towards the
beginning of the array
 reset moves the pointer to the beginning of
the array
 PHP provides the array_push function that
appends its arguments to a given array
 The function array_pop removes the last
element of a given array and returns it

33
Iterating Through an Array
 The foreach statement has two forms for iterating through
an array
foreach (array as scalar_variable) loop
body
foreach (array as key => value) loop body
 The first version assigns each value in the array to the
scalar_variable in turn
 The second version assigns each key to key and the
associated value to value in turn
 In this example, each day and temperature is printed
$lows = array("Mon" => 23, "Tue" => 18, "Wed"
=> 27);
foreach ($lows as $day => $temp)
print("The low temperature on $day was $temp
<br />");

34
Embedding code in web pages
 most PHP programs actually produce HTML as
their output
◦ dynamic pages; responses to HTML form submissions;
etc.
 an embedded PHP program is a file that
contains a mixture of HTML and PHP code

35
Printing HTML tags in PHP = bad
style
<?php
print "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n";
print " \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n";
print "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
print " <head>\n";
print " <title>Geneva's web page</title>\n";
...
for ($i = 1; $i <= 10; $i++) {
print "<p> I can count to $i! </p>\n";
}
?>

•Printing HTML tags with print statements is bad style and error-prone:
- Must quote the HTML and escape special characters, e.g. \"
- Best PHP style is to minimize print/echo statements in embedded
PHP code
•But without print, how do we insert dynamic content into the page?
36
Functions
 Function syntax:
function name([parameters]) {
...
}
 The parameters are optional, but not the
parentheses
 Function names are case insensitive
 A return statement causes the function to
immediately terminate and return a value, if any,
provided in the return
 A function that reaches the end of the body
without executing a return, returns no value

37
Parameters
 A formal parameter, specified in a function
declaration, is simply a variable name
 If more actual parameters are supplied in a call than
there are formal parameters, the extra values are
ignored
 If more formal parameters are specified than there
are actual parameters in a call then the extra formal
parameters receive no value
 PHP defaults to pass by value
◦ Putting an ampersand “&” in front of a formal parameter
specifies that pass-by-reference
◦ An ampersand can also be appended to the actual
parameter (which must be a variable name)

38
Variable scope
$Last_Name = ""; // global
...
function myFunc() {
global $Last_Name;
$first_Name= ”Norah"; // local
$Last_Name = “$Last_Name $first_Name”;
print " $Last_Name ";
}

• Variables declared in a function are local to that function


• Variables not declared in a function are global
• If a function wants to use a global variable, it must have a
global statement

39

You might also like