Web Programming Step by Step, 2nd Edition
Lecture 7: Embedded PHP
Reading: 5.3 - 5.5
Except where otherwise noted, the contents of this document are
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst.
All rights reserved.
Any redistribution, reproduction, transmission, or storage of part
or all of the contents in any form is prohibited without the author's
expressed written permission.
5.2: PHP Basic Syntax
-
5.1: Server-Side Basics
-
5.2: PHP Basic Syntax
-
5.3: Embedded PHP
-
5.4: Advanced PHP Syntax
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
- can switch back and forth between HTML and PHP "modes"
int
and float
types
$a = 7 / 2;
$b = (int) $a;
$c = round($a);
$d = "123";
$e = (int) $d;
int
for integers and float
for reals
- division between two
int
values can produce a float
$favorite_food = "Ethiopian";
print $favorite_food[2];
- zero-based indexing using bracket notation
- string concatenation operator is
.
(period), not +
5 + "2 turtle doves"
produces 7
5 . "2 turtle doves"
produces "52 turtle doves"
- can be specified with
""
or ''
Interpreted strings
$age = 16;
print "You are " . $age . " years old.\n";
print "You are $age years old.\n";
String
functions
$name = "Stefanie Hatcher";
$length = strlen($name);
$cmp = strcmp($name, "Brian Le");
$index = strpos($name, "e");
$first = substr($name, 9, 5);
$name = strtoupper($name);
bool (Boolean) type
$feels_like_summer = FALSE;
$php_is_rad = TRUE;
$student_count = 217;
$nonzero = (bool) $student_count;
- the following values are considered to be
FALSE
(all others are TRUE
):
-
0
and 0.0
-
""
, "0"
, and NULL
(includes unset variables)
- arrays with 0 elements
- can cast to boolean using
(bool)
FALSE
prints as an empty string (no output); TRUE
prints as a 1
TRUE
and FALSE
keywords are case insensitive
$a = 3;
$b = 4;
$c = sqrt(pow($a, 2) + pow($b, 2));
math constants
M_PI
|
M_E
|
M_LN2
|
- the syntax for method calls, parameters, returns is the same as Java
NULL
$name = "Victoria";
$name = NULL;
if (isset($name)) {
print "This line isn't going to be reached.\n";
}
- a variable is
NULL
if
- it has not been set to any value (undefined variables)
- it has been assigned the constant
NULL
- it has been deleted using the
unset
function
- can test if a variable is
NULL
using the isset
function
NULL
prints as an empty string (no output)
$name = array();
$name = array(value0, value1, ..., valueN);
$name[index]
$name[index] = value;
$name[] = value;
$a = array();
$a[0] = 23;
$a2 = array("some", "strings", "in", "an", "array");
$a2[] = "Ooh!";
- to append, use bracket notation without specifying an index
- element type is not specified; can mix types
Array functions
function name(s)
|
description
|
count
|
number of elements in the array
|
print_r
|
print array's contents
|
array_pop ,
array_push ,
array_shift ,
array_unshift
|
using array as a stack/queue
|
in_array ,
array_search ,
array_reverse ,
sort ,
rsort ,
shuffle
|
searching and reordering
|
array_fill ,
array_merge ,
array_intersect ,
array_diff ,
array_slice ,
range
|
creating, filling, filtering
|
array_sum ,
array_product ,
array_unique ,
array_filter ,
array_reduce
|
processing elements
|
Array function example
$tas = array("MD", "BH", "KK", "HM", "JP");
for ($i = 0; $i < count($tas); $i++) {
$tas[$i] = strtolower($tas[$i]);
}
$morgan = array_shift($tas);
array_pop($tas);
array_push($tas, "ms");
array_reverse($tas);
sort($tas);
$best = array_slice($tas, 1, 2);
-
the array in PHP replaces many other collections in Java
-
list, stack, queue, set, map, ...
The foreach
loop
foreach ($array as $variableName) {
...
}
$stooges = array("Larry", "Moe", "Curly", "Shemp");
for ($i = 0; $i < count($stooges); $i++) {
print "Moe slaps {$stooges[$i]}\n";
}
foreach ($stooges as $stooge) {
print "Moe slaps $stooge\n";
}
- a convenient way to loop over each element of an array without indexes
Functions
function name(parameterName, ..., parameterName) {
statements;
}
function bmi($weight, $height) {
$result = 703 * $weight / $height / $height;
return $result;
}
- parameter types and return types are not written
- a function with no
return
statements is implicitly "void"
- can be declared in any PHP block, at start/end/middle of code
Calling functions
name(expression, ..., expression);
$w = 163;
$h = 70;
$my_bmi = bmi($w, $h);
- if the wrong number of parameters are passed, it's an error
Variable scope: global and local vars
$school = "UW";
...
function downgrade() {
global $school;
$suffix = "(Wisconsin)";
$school = "$school $suffix";
print "$school\n";
}
- variables declared in a function are local to that function; others are global
- if a function wants to use a global variable, it must have a
global
statement
- but don't abuse this; mostly you should use parameters
Default parameter values
function name(parameterName = value, ..., parameterName = value) {
statements;
}
function print_separated($str, $separator = ", ") {
if (strlen($str) > 0) {
print $str[0];
for ($i = 1; $i < strlen($str); $i++) {
print $separator . $str[$i];
}
}
}
print_separated("hello");
print_separated("hello", "-");
- if no value is passed, the default will be used (defaults must come last)
5.3: Embedded PHP
-
5.1: Server-Side Basics
-
5.2: PHP Basic Syntax
-
5.3: Embedded PHP
-
5.4: Advanced PHP Syntax
Printing HTML tags in PHP = bad style
<?php
print "<!DOCTYPE html>\n";
print "<html>\n";
print " <head>\n";
print " <title>Geneva's web page</title>\n";
...
for ($i = 1; $i <= 10; $i++) {
print "<p class=\"count\"> 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.
\"
- but without
print
, how do we insert dynamic content into the page?
PHP expression blocks
<?= expression ?>
<h2> The answer is <?= 6 * 7 ?> </h2>
The answer is 42
-
PHP expression block: evaluates and embeds an expression's value into HTML
-
<?= expr ?>
is equivalent to <?php print expr; ?>
Expression block example
<!DOCTYPE html>
<html>
<head><title>CSE 190 M: Embedded PHP</title></head>
<body>
<?php for ($i = 99; $i >= 1; $i--) { ?>
<p> <?= $i ?> bottles of beer on the wall, <br />
<?= $i ?> bottles of beer. <br />
Take one down, pass it around, <br />
<?= $i - 1 ?> bottles of beer on the wall. </p>
<?php } ?>
</body>
</html>
Common errors: unclosed braces, missing = sign
<body>
<p>Watch how high I can count:
<?php for ($i = 1; $i <= 10; $i++) { ?>
<? $i ?>
</p>
</body>
</html>
Complex expression blocks
<body>
<?php for ($i = 1; $i <= 3; $i++) { ?>
<h<?= $i ?>>This is a level <?= $i ?> heading.</h<?= $i ?>>
<?php } ?>
</body>
This is a level 1 heading.
This is a level 2 heading.
This is a level 3 heading.
- expression blocks can even go inside HTML tags and attributes