COMP519 Web Programming
Lecture 20: PHP (Part 2)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 Comparisons
2 Arrays
Basics
Foreach-loops
Array Operators
3 Special types
NULL
Resources
4 Printing
5 Revision and Further Reading
COMP519 Web Programming Lecture 20 Slide L20 1
Comparisons
Comparison Operators
Type juggling also plays a role in the way PHP comparison operators work:
expr1 == expr2 Equal TRUE iff expr1 is equal to expr2
after type juggling
expr1 != expr2 Not equal TRUE iff expr1 is not equal to expr2
after type juggling
expr1 <> expr2 Not equal TRUE iff expr1 is not equal to expr2
after type juggling
expr1 === expr2 Identical TRUE iff expr1 is equal to expr2,
and they are of the same type
expr1 !== expr2 Not identical TRUE iff expr1 is not equal to expr2,
or they are not of the same type
Note: For ==, !=, and <>, numerical strings are converted to numbers
and compared numerically
"123" == 123 ; TRUE "123" === 123 ; FALSE
"123" != 123 ; FALSE "123" !== 123 ; TRUE
"1.23e2" == 123 ; TRUE 1.23e2 === 123 ; FALSE
"1.23e2" == "12.3e1" ; TRUE "1.23e2" === "12.3e1" ; FALSE
"10hello5" == 10 ; TRUE "10hello5" === 10" ; FALSE
5 == TRUE ; TRUE 5 === TRUE ; FALSE
COMP519 Web Programming Lecture 20 Slide L20 2
Comparisons
Comparison Operators
Type juggling also plays a role in the way PHP comparison operators work:
expr1 < expr2 Less than TRUE iff expr1 is strictly less than expr2
after type juggling
expr1 > expr2 Greater than TRUE iff expr1 is strictly greater than expr2
after type juggling
expr1 <= expr2 Less than
or equal to
TRUE iff expr1 is less than or equal to expr2
after type juggling
expr1 >= expr2 Greater than
or equal to
TRUE iff expr1 is greater than or equal to expr2
after type juggling
Note: For >, >=, <, and <= numerical strings are converted to numbers
and compared numerically
'35.5' > 35 ; TRUE '35.5' >= 35 ; TRUE
'ABD' > 'ABC' ; TRUE 'ABD' >= 'ABC' ; TRUE
'1.23e2' > '12.3e1' ; FALSE '1.23e2' >= '12.3e1' ; TRUE
"F1" < "G0" ; TRUE "F1" <= "G0" ; TRUE
TRUE > FALSE ; TRUE TRUE >= FALSE ; TRUE
5 > TRUE ; FALSE 5 >= TRUE ; TRUE
COMP519 Web Programming Lecture 20 Slide L20 3
Comparisons
Comparison operators
To compare strings ‘as strings’ the strcmp function can be used
PHP 7 introduced the so-called ‘spaceship operator’ for three-way
comparisons (that converts numeric strings to numbers)
strcmp(expr1,expr2) String
comparison
Returns < 0 if expr1 is less than expr2,
> 0 if expr1 is greater than expr2,
0 if expr1 is equal to expr2
expr1 <=> expr2
(PHP 7 only)
Three-way
comparison
Returns -1 if expr1 < expr2,
+1 if expr1 > expr2,
0 if expr1 == expr2
strcmp('ABD','ABC') ; 1 strcmp("F1","G0") ; -65536
strcmp('aaa',"aaa") ; 0 strcmp('aaa',"AAA") ; 2105376
strcmp('1.23e2','12.3e1') ; -1
'ABD' <=> 'ABC' ; 1 "F1" <=> "G0" ; -1
'aaa' <=> "aaa" ; 0 'aaa' <=> "AAA" ; 1
'1.23e2' <=> '12.3e1' ; 0
'35.5' <=> 35 ; 1 '10hello5' <=> 10 ; 0
TRUE <=> FALSE ; 1 0.0 <=> FALSE ; 0
5 <=> TRUE ; 0 'FALSE' <=> TRUE ; 0
COMP519 Web Programming Lecture 20 Slide L20 4
Comparisons
Integers and Floating-point numbers: NAN and INF
NAN and INF can be compared with each other and other numbers using
equality and comparison operators:
NAN == NAN ; FALSE NAN === NAN ; FALSE NAN == 1 ; FALSE
INF == INF ; TRUE INF === INF ; TRUE INF == 1 ; FALSE
NAN < NAN ; TRUE INF < INF ; TRUE 1 < INF ; TRUE
NAN < INF ; TRUE INF < NAN ; TRUE INF < 1 ; FALSE
NAN < 1 ; TRUE 1 < NAN ; TRUE
In PHP 5.3 and earlier versions, INF == INF returns FALSE
INF === INF returns TRUE
In PHP 5.4 and later versions, INF == INF returns TRUE
INF === INF returns TRUE
COMP519 Web Programming Lecture 20 Slide L20 5
Comparisons
Integers and Floating-point numbers: NAN and INF
PHP provides three functions to test whether a value is or is not NAN,
INF or -INF:
bool is_nan(value)
returns TRUE iff value is NAN
bool is_infinite(value)
returns TRUE iff value is INF or -INF
bool is_finite(value)
returns TRUE iff value is neither NAN nor INF/-INF
In conversion to a boolean value,
both NAN and INF are converted to TRUE
In conversion to a string,
NAN converts to 'NAN' and
INF converts to 'INF'
COMP519 Web Programming Lecture 20 Slide L20 6
Arrays Basics
Arrays
PHP only supports associative arrays (hashes), simply called arrays
PHP arrays are created using the array construct or,
since PHP 5.4, [ ... ]:
array ( key => value , ... )
[ key => value , ...]
where key is an integer or string and value can be of any type,
including arrays
$arr1 = [1 => " Peter " , 3 => 2009 , "a " => 101];
$arr2 = array (2008 46 36 9 = > array (" name " => " Jan Olsen " ,
" COMP51 8 " => 69 ,
" COMP51 9 " => 52 ));
The size of an array can be determined using the count function:
int count(array[, mode])
print count ( $arr1 ); // prints 3
print count ( $arr2 ); // prints 1
print count ( $arr2 ,1); // prints 4
COMP519 Web Programming Lecture 20 Slide L20 7
Arrays Basics
Arrays
It is possible to omit the keys when using the array construct:
$arr3 = array (" Peter " , "Paul " , " Mary " );
The values given in array will then be associated with the
natural numbers 0, 1, . . .
All the keys of an array can be retrieved using
array_keys($array1)
; returns a natural number-indexed array containing
the keys of $array1
All the values of an array can be retrieved using
array_values($array1)
; returns a natural number-indexed array containing
the values stored in $array1
COMP519 Web Programming Lecture 20 Slide L20 8
Arrays Basics
Arrays
An individual array element can be accessed via its key
Accessing an undefined key produces a PHP notice
and returns NULL
$arr1 = array (1 = > "Peter " , 3 => 2009 , "a " => 101);
print " 'a ' = > " . $arr1 [ "a" ]. "\ n" ;
'a ' = > 101
print " 'b ' = > " . $arr1 [ "b" ]. "\ n" ;
PHP Notice : Undef in ed index : b in < file > on line < lineno >
'b ' = > // $arr1 [" b"] re turn s NULL
$arr1 [ 'b '] = 102;
print " 'b ' = > " . $arr1 [ "b" ]. "\ n" ;
'b ' = > 102
The function array_key_exists(key,array1) can be used to check
whether there is a value for key in array1
arr ay _key _e xists ("a ", $arr1 ) # ret urns TRUE
arr ay _key _e xists ("c ", $arr1 ) # ret urns FALSE
COMP519 Web Programming Lecture 20 Slide L20 9
Arrays Basics
Arrays
PHP allows the construct
$ array [] = value ;
PHP will determine the maximum value M among the integer indices in
$array and use the key K = M + 1; if there are no integer indices in
$array, then K = 0 will be used
; auto-increment for array keys
$arr4 [] = 51; // 0 = > 51
$arr4 [] = 42; // 1 = > 42
$arr4 [] = 33; // 2 = > 33
A key-value pair can be removed from an array using the
unset function:
$arr1 = array (1 = > "Peter " , 3 => 2009 , "a " => 101);
unset ( $arr1 [3]); // Removes the pair 3 => 2009
unset ( $arr1 ); // Removes the whole array
COMP519 Web Programming Lecture 20 Slide L20 10
Arrays Foreach-loops
Arrays: foreach-loop
PHP provides a foreach-loop construct to ‘loop’ through the elements
of an array
foreac h ( array as $ value )
stat eme nt
foreac h ( array as $ key = > $ value )
stat eme nt
array is an array expression
$key and $value are two variables, storing a different key-value pair in
array at each iteration of the foreach-loop
We call $value the foreach-variable
foreach iterates through an array in the order in which elements were
defined
COMP519 Web Programming Lecture 20 Slide L20 11
Arrays Foreach-loops
Arrays: foreach-loop
foreach iterates through an array in the order in which elements were
defined
Example 1:
foreac h ( array (" Peter " , " Paul ", " Mary " ) as $ key => $ value )
print " The array maps $key to $value \ n";
The array maps 0 to Peter
The array maps 1 to Paul
The array maps 2 to Mary
Example 2:
$arr5 [2] = " Mary ";
$arr5 [0] = " Peter " ;
$arr5 [1] = " Paul ";
// 0 = > ' Peter ', 1 = > ' Paul ' , 2 = > ' Mary '
foreac h ( $arr5 as $ key = > $value )
print " The array maps $key to $value \ n";
The array maps 2 to Mary
The array maps 0 to Peter
The array maps 1 to Paul
COMP519 Web Programming Lecture 20 Slide L20 12
Arrays Foreach-loops
Arrays: foreach-loop
Does changing the value of the foreach-variable change the element of the
list that it currently stores?
Example 3:
$arr6 = array (" name " = > " Peter " , " year " = > 200 9);
foreac h ( $arr6 as $ key = > $value ) {
print " The array maps $key to $value \ n";
$value .= " - modified "; // Cha ngi ng $ v alue
}
print "\ n";
The array maps name to Peter
The array maps year to 2009
foreac h ( $arr6 as $ key = > $value )
print " The array now maps $key to $value \n ";
The array now maps name to Pete r
The array now maps year to 2009
COMP519 Web Programming Lecture 20 Slide L20 13
Arrays Foreach-loops
Arrays: foreach-loop
In order to modify array elements within a foreach-loop we need use a
reference
foreac h ( array as & $ value )
stat eme nt
unset ($ value );
foreac h ( array as $ key = > &$ value )
stat eme nt
unset ($ value );
In the code schemata above, $value is a variable whose value is stored at
the same location as an array element
PHP does not allow the key to be a reference
The unset statement is important to return $value to being a ‘normal’
variable
COMP519 Web Programming Lecture 20 Slide L20 14
Arrays Foreach-loops
Arrays: foreach-loop
In order to modify array elements within a foreach-loop we need use a
reference
In each iteration, $value contains a reference to an array element
; changing $value changes the array element
$arr6 = array (" name " = > " Peter " , " year " = > 200 9);
foreac h ( $arr6 as $ key = > & $ value ) { // Note : r efere nce !
print " The array maps $key to $value \ n";
$value .= " - modified ";
}
unset ( $value ); // Remove the re fer en ce from $value
print "\ n";
The array maps name to Peter
The array maps year to 2009
// See what the co nten t of $ arr6 is now
foreac h ( $arr6 as $ key = > $value )
print " The array now maps $key to $value \n ";
The array now maps name to Pete r - modi fie d
The array now maps year to 2009 - mod ified
COMP519 Web Programming Lecture 20 Slide L20 15
Arrays Foreach-loops
Array Assignments
In JavaScript arrays were objects and as a consequence array
assignments were done by reference
In PHP, this is not the case
$m em1 = memory _ g e t _ u s a ge ();
$ar ray1 = r ang e (1 , 1000);
$m em2 = memory _ g e t _ u s a ge ();
echo " (1) " ,spri ntf (" %6d " ,$ mem2 - $ mem1 )," more b yte s \n";
$ar ray2 = $ar ray1 ;
$m em3 = memory _ g e t _ u s a ge ();
echo " (2) " ,spri ntf (" %6d " ,$ mem3 - $ mem2 )," more b yte s \n";
$ar ray2 [1] += 1 0000 ;
echo "\ $a rray1 [1] = ", $a rray1 [1] ," | " ;
echo "\ $a rray2 [1] = ", $a rray2 [1] ,"\ n " ;
$m em4 = memory _ g e t _ u s a ge ();
echo " (3) " ,spri ntf (" %6d " ,$ mem4 - $ mem3 )," more b yte s \n";
(1) 36920 more bytes
(2) 0 more bytes
$ar ray1 [1] = 2 | $ arra y2 [1] = 10 002
(3) 36920 more bytes
The PHP implementation uses copy-on-write for array assignments
COMP519 Web Programming Lecture 20 Slide L20 16
Arrays Foreach-loops
Array Assignments
The PHP implementation uses copy-on-write for array assignments
If we want two array variables to point to the same array literal,
then we need to explicitly use a reference
$array 1 = range (1 , 100 0);
$mem2 = me mory _g et _usa ge ();
$array 2 = & $arra y1 ;
$mem3 = me mory _g et _usa ge ();
echo " (2) " ,s prin tf ( "%6 d" ,$mem3 - $mem2 ) ," more bytes \n ";
$array 2 [1] += 10000;
echo " \ $array1 [1] = " ,$ a rray 1 [1] , " | " ;
echo " \ $array2 [1] = " ,$ a rray 2 [1] , "\n ";
$mem4 = me mory _g et _usa ge ();
echo " (3) " ,s prin tf ( "%6 d" ,$mem4 - $mem3 ) ," more bytes \n ";
(2) 24 more bytes
$array 1 [1] = 10002 | $ a rray 2 [1] = 10002
(3) 0 more bytes
COMP519 Web Programming Lecture 20 Slide L20 17
Arrays Array Operators
Array Operators
PHP has no stack or queue data structures,
but has stack and queue operators for arrays:
array_push(&$array, value1, value2,...)
appends one or more elements at the end of the end of an array variable;
returns the number of elements in the resulting array
array_pop(&$array)
extracts the last element from an array and returns it
array_shift(&$array)
shift extracts the first element of an array and returns it
array_unshift(&$array, value1, value2,...)
inserts one or more elements at the start of an array variable;
returns the number of elements in the resulting array
Note: &$array needs to be a variable
COMP519 Web Programming Lecture 20 Slide L20 18
Special types NULL
NULL
NULL is both a special type and a value
NULL is the only value of type NULL
and the name of this constant is case-insensitive
A variable has both type NULL and value NULL in the following three
situations:
1 The variable has not yet been assigned a value (not equal to NULL)
2 The variable has been assigned the value NULL
3 The variable has been unset using the unset operation
There are a variety of functions that can be used to test whether a
variable is NULL including:
bool isset($variable)
TRUE iff $variable exists and does not have value NULL
bool is_null(expr)
TRUE iff expr is identical to NULL
COMP519 Web Programming Lecture 20 Slide L20 19
Special types NULL
NULL
Warning: Using NULL with == may lead to counter-intuitive results
$d = array ();
echo v ar_ dum p ($d ), " \n" ;
array (0) {
}
echo ' is_null ( $d ): ' , ( is_ null ($d )) ? " TRUE \n " : " FALSE \ n";
is_nul l ($d ): FALSE
echo ' $d === null : ' , ( $d === null ) ? " TRUE \ n" : " FALSE \ n";
$d === null : FALSE
echo ' $d == null : ' , ( $d == null ) ? " TRUE \n" : " FALSE \ n";
$d == null : TRUE
Type juggling means that an empty array is (loosely) equal to NULL
but not identical (strictly equal) to NULL
COMP519 Web Programming Lecture 20 Slide L20 20
Special types Resources
Resources
A resource is a reference to an external resource
resource fopen(filename, mode)
Returns a file pointer resource for filename access using mode on
success, or FALSE on error
Mode Operation Create Truncate
’r’ read file
’r+’ read/write file
’w’ write file yes yes
’w+’ read/write file yes yes
’a’ append file yes
’a+’ read/append file yes
’x’ write file yes
’x+’ read/write file yes
See http://www.php.net/manual/en/resource.php for further details
COMP519 Web Programming Lecture 20 Slide L20 21
Special types Resources
Resources
bool fclose(resource)
Closes the resource
Returns TRUE on success
string fgets(resource [, length])
Returns a line read from resource and
returns FALSE if there is no more data to be read
With optional argument length, reading ends when length 1 bytes
have been read, or a newline or on EOF (whichever comes first)
string fread(resource,length)
Returns length characters read from resource
$handl e = fopen ( ' som efi le . txt ' , ' r ' );
while ( $line = fgets ( $ hand le )) {
// pro ce ssi ng the line of the file
}
fclose ( $ ha ndle );
COMP519 Web Programming Lecture 20 Slide L20 22
Special types Resources
Resources
int fwrite(resource, string [, length])
Writes a string to a resource
If length is given, writing stops after length bytes have been written or
the end of string is reached, whichever comes first
int fprintf(resource, format, arg1, arg2, ...)
Writes a list of arguments to a resource in the given format
Identical to fprintf with output to resource
int vfprintf (resource, format, array)
Writes the elements of an array to a resource in the given format
Identical to vprintf with output to resource
$handl e = fopen ( ' som efi le . txt ' , ' w ' );
fwrite ( $handle ," Hello World !" . PHP_EOL ); // ` logic al n ewli ne '
fclose ( $ ha ndle );
In PHP \n always represents the character with ASCII code 10 not the
platform dependent newline ; use PHP_EOL instead
COMP519 Web Programming Lecture 20 Slide L20 23
Printing
Printing
In PHP, the default command for generating output is echo
void echo(arg1)
void echo arg1, arg2, ...
Outputs all arguments
No parentheses are allowed if there is more than one argument
More efficient than print (and therefore preferred)
Additionally, PHP also provides the functions print, and printf:
int print(arg)
Outputs its argument
Only one argument is allowed!
Returns value 1
Parentheses can be omitted
COMP519 Web Programming Lecture 20 Slide L20 24
Printing
Printing
string sprintf(format, arg1, arg2, ....)
Returns a string produced according to the formatting string format
Parentheses are necessary
See http://www.php.net/manual/en/function.sprintf.php
for details
int printf(format, arg1, arg2, ...)
Produces output according to format
Parentheses are necessary
Returns the length of the outputted string
Important: A PHP array cannot take the place of a list of argu-
ments
printf ( "%2 d apples %2 d oran ges \ n" ,array (5 ,7));
produces a PHP warning and no output
COMP519 Web Programming Lecture 20 Slide L20 25
Printing
Printing
string vsprintf(format, array)
Returns a string produced according to the formatting string format
Identical to sprintf but accepts an array as argument
Parentheses are necessary
int vprintf(format, array)
Produces output according to format
Identical to printf but accepts an array as argument
Parentheses are necessary
vprint f (" %2 d apples %2 d orang es \ n" ,array (5 ,7));
5 apples 7 o rang es
COMP519 Web Programming Lecture 20 Slide L20 26
Revision and Further Reading
Revision and Further Reading
Read
Chapter 4: Expressions and Control Flow in PHP: Operators
Chapter 6: PHP Arrays
of R. Nixon: Learning PHP, MySQL & JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
Read
Language Reference: Types: Arrays
http://uk.php.net/manual/en/language.types.array.php
Language Reference: Control Structures: foreach
http://uk.php.net/manual/en/control-structures.foreach.php
of P. Cowburn (ed.): PHP Manual. The PHP Group, 25 Oct 2019.
http://uk.php.net/manual/en [accessed 26 Oct 2019]
COMP519 Web Programming Lecture 20 Slide L20 27