Docsity

PHP Language Elements: Data Types, Operators, Conditionals, and Functions Summary - Prof. , Assignments of Biology

Toggle sidebar
bg1
4. Summary of Selected
PHP Language
Elements
This chapter provides a summary of PHP language elements that are
needed or helpful for creating the kinds of applications that have been
discussed in this book. As with other parts of this book, the descriptions
are neither comprehensive nor necessarily complete, and are not intended
to take the place of a reference manual. Nonetheless, the examples
presented in this chapter cover a large range of practical PHP
programming situations.
4.1 Data Types and Operators
4.1.1 Data Types
PHP supports four scalar primitive data types:
boolean (bool)
integer (int)
float (float)
string (string)
Boolean data can have values of true or false. The maximum
size of an integer that can be represented is system-dependent, but
integers are often represented with a 32-bit word, with one bit allocated
for a sign. (PHP does not support unsigned integers.) This gives a
maximum integer value of 2,147,483,647. If presented with an integer
larger than the allowed maximum, PHP will convert it to a floating point
number, possibly with some loss of precision. The precision of floating
point numbers is also system-dependent but is often about 14 digits.
Sometimes you will find references to a “double” data type. In C, for
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Partial preview of the text

Download PHP Language Elements: Data Types, Operators, Conditionals, and Functions Summary - Prof. and more Assignments Biology in PDF only on Docsity!

4. Summary of Selected

PHP Language

Elements

This chapter provides a summary of PHP language elements that are needed or helpful for creating the kinds of applications that have been discussed in this book. As with other parts of this book, the descriptions are neither comprehensive nor necessarily complete, and are not intended to take the place of a reference manual. Nonetheless, the examples presented in this chapter cover a large range of practical PHP programming situations.

4.1 Data Types and Operators

4.1.1 Data Types PHP supports four scalar primitive data types: boolean (bool) integer (int) float (float) string (string) Boolean data can have values of true or false. The maximum size of an integer that can be represented is system-dependent, but integers are often represented with a 32-bit word, with one bit allocated for a sign. (PHP does not support unsigned integers.) This gives a maximum integer value of 2,147,483,647. If presented with an integer larger than the allowed maximum, PHP will convert it to a floating point number, possibly with some loss of precision. The precision of floating point numbers is also system-dependent but is often about 14 digits. Sometimes you will find references to a “double” data type. In C, for

2 4. Summary of Selected PHP Language Elements

example, the precision of “float” and “double” real-number values is different, but there is no such distinction in PHP, which supports only a single floating point number representation. Strings are composed of 8-bit characters (giving 256 possible characters), with no imposed limit on string length. PHP supports arrays and objects as compound data types. This book deals only with the (array) type, which can be used to aggregate a mixture of data types under a single name. Arrays elements can be any of the primitive data types, as well as other arrays. When a collection of data with various types is specified, such as the elements of a mixed-type array, they can be identified for convenience as (mixed) , but this word represents only a “pseudo” data type, not an actual data type specification. In the definitions of math functions given below in Table 4.5, inputs and outputs are sometimes identified as having a (number) data type. This is also a “pseudo” data type that can be either an integer or a floating point number, depending on context. 4.1.2 Operators PHP supports a large number of operators, some of which are listed in Table 4.1, in order of precedence. Table 4.1. Operators, in decreasing order of precedence. Operator Description ++, -- increment/decrement *, /, % multiplication, division, modulus division +, - ,. addition, subtraction, string concatenation <, <=, >, >= relational comparisons ==, !=, ===, !== relational comparisons &&(1)^ logical AND ||(1)^ logical OR =, +=, -=, *=, /=, %=, .= arithmetic assignment, string concatenation assignment and (^) logical AND xor (^) logical EXCLUSIVE OR or (^) logical OR (1) (^) Note the availability of two AND (&& and and) and two OR (|| and or) operators, at different precedence levels. (and and or have lower precedence than && and ||.)

4 4. Summary of Selected PHP Language Elements

i equals 2

There are two real roots.

This function calculates roots...

Print the roots here...

4.2.2 Case-controlled conditional execution

PHP also has a “switch” construct. switch ( $i ) { case 0 : echo "i equals 0."; break ; case 1 : echo "i equals 1."; break ; case 2 : echo "i equals 2."; break ; default : echo "i does not equal 0, 1, or 2."; } The order of the case values does not matter. Unlike the if… construct, in which only the first “true” path is executed, the break; statement is needed to exit the construct after the first case match is encountered. Otherwise, all subsequent statements within the construct are executed; there are certainly circumstances under which this might be the desired result, in which case the break; statements wouldn’t be needed, although the order of the case values probably would matter. Multiple case values can be associated with the same action, as shown in Document 4.2. Document 4.2 (daysInMonth.php) <?php $month =5; switch ( $month ) { case 1: case 3: case 5: case 7: case 8:

case 10: case 12: echo "There are 31 days in this month.
"
; break ; case 4: case 6: case 9: case 11: echo "There are 30 days in this month.
"
; break ; case 2: echo _"There are either 28 or 29 days in this month.<br /

"_ ; break ;

default : echo "I do not understand your month entry." ; } ?>

There are 31 days in this month.

In PHP, case values can be strings: switch ( $fruit ) case "apple" : echo "This is an apple." ; break ; case "orange" : echo "This is an orange." ; break ; case "banana" : echo "This is a banana." ; break ; default : echo "This is not an allowed fruit treat." ; } Comparisons against the value to be tested are case-sensitive. So, if $fruit is assigned as $fruit = "Banana"; prior to the switch construct, (instead of $fruit = "banana";, for example) the default message is printed.

4.3 Loops

PHP supports both count-controlled and conditional execution loops, including a loop (foreach…) designed specifically for accessing keyed arrays. In the examples below, generic variable names such as $counter ,

4 => "PHP" ); foreach ( $a as $k => $x ) echo "a[". $k. "] = ". $x. "
"
; $b = array (77, 33, 4); foreach ( $b as $x ) { echo ( " $x ". "
"
); } ?>

stringThing

PHP

stringThing

PHP

a[1] = 17

a[2] = -13.

a[3] = stringThing

a[4] = PHP

The foreach… loop iterates over keyed elements in an array, including arrays with other than integer indices. The curly brackets are optional if there is only one statement. foreach ( (array) $a as $value ) { {one or more statements} } foreach ( (array) $a as $key => $value ) { {one or more statements} } Example: Document 4.5 (foreach.php)

8 4. Summary of Selected PHP Language Elements

<?php $a = array (17,-13.3, "stringThing" , "PHP" ); foreach ( $a as $x ) echo " $x
"
; $a = array (1 => 17,2 => -13.3, 3 => "stringThing" , 4 => "PHP" ); foreach ( $a as $k => $x ) echo "a[". $k. "] = ". $x. "
"
; ?>

stringThing

PHP

a[1] = 17

a[2] = -13.

a[3] = stringThing

a[4] = PHP

4.3.2 Condition-Controlled Loops

do ( {one or more statements} } while ( (bool) {logical expression} ); The conditional do… loop executes statements as long as the {logical expression} evaluates as true. Because the expression is evaluated at the end of the loop, the statements inside the loop will always be executed at least once. while ( {logical expression} ) { {one or more statements} } The conditional while… loop executes statements as long as the {logical expression} evaluates as true. Because the expression is evaluated before statements are executed, it is possible that the statements inside a while… loop will never be executed. Examples:

10 4. Summary of Selected PHP Language Elements

variable names are given in italicized Courier font , e.g., $fileHandle. Optional parameters are enclosed in square brackets.

4.4.1 File Handling and I/O Functions

Often, you will use PHP to process input values passed from another document. What you might consider providing as input from the keyboard, as you can easily do in C, for example, is not at all trivial in a PHP online application, and is system-dependent. So, the assumption in this book is that all “keyboard” input will be provided through form fields in an HTML document and that any other required input will come from external files. After all, file access is the primary justification given in this book for using a server-side language. Format specifiers: I/O functions that read input or display output require format specifiers that control how input is interpreted and how output is displayed. Each output format conversion specifier starts with a percent sign (%) followed by, in order, one or more of these optional elements: Sign specifier Either a “-” or a “+” forces numbers to be displayed with a leading sign. (By default, negative numbers are preceded by a “-” sign, but positive numbers are not preceded by a “+” sign.) Padding specifier Specifies a character, preceded by a single quote ('), used for padding numerical results to the appropriate string size. The default character is a space. A typical non-default character would be a 0. Alignment specifier By default, output is right-justified. Including a “-” will force left-justification. Width specifier Defines the minimum number of spaces allocated for display of a number or string. If the width specifier is too small, it will be overridden to allow display of the entire number or string. Precision specifier

Preceded by a decimal point, defines how many digits to the right of the decimal point should be displayed for floating-point numbers. Often used along with the width specifier, e.g. , 8.3. When applied to a string, this value defines the maximum number of characters displayed. When significant digits are lost, the result is rounded rather than truncated. For example, an n .3 specifier applied to 17.4567 is displayed as 17.457. Finally, a required type specifier for input or output defines how an argument should be interpreted and displayed. Some type specifiers for strings and base-10 numbers are given in Table 4.2. Format strings can have other embedded characters, too. For example, the statement fscanf($inFile,"%u,%f",$i,$x); implies that a line in the input file contains an integer and a floating point number, with a comma directly after the integer. The number of spaces between a comma and the following number does not matter. For example, it does not matter whether two values in a file are stored as 17,33. or 17, 33. The same format specifier used for output would display one integer and one floating point number in default format, separated by a comma. With output, multiple spaces embedded in a format string are collapsed into a single space when they are displayed in a browser, but those spaces are retained if the output is sent to a file. Table 4.2. Selected type specifiers for input and formatted output. Specifier Description c Treats argument as an integer, displays it as the character having that base-10 ASCII value. d (^) Displays numerical value as a signed base-10 integer. E Displays numerical value in scientific notation, e.g. , 7.444e-3. f (^) Displays numerical value as a floating-point number. s (^) Displays argument as a string.

usually a string literal. The mode string can be surrounded by either single or double quotes. There are several possible modes for opening files, including binary files, but this book will assume all files are text files and will be opened either for reading or writing, but not for both simultaneously. A summary of the three modes are given in Table 4.4. Table 4.4. Text file access modes for fopen(). Mode Description "r" (^) Open for reading only, starting at beginning of file. "w" (^) Open for writing only. If file exists, its contents will be overwritten. If not, it will be created. "a" (^) Open for writing only, starting at the end of an existing file. If the file doesn't it exist, it will be created. With these access modes, all files are “sequential access” as opposed to “random access.” When a file is opened in read-only mode, its file handle points to the location of the first byte of the file in memory. Reading from such a file implies that you have to read all the contents of the file, starting at the beginning, even if you discard some of the information. You cannot jump to some random location within the file In write-only mode, data are written to the file sequentially, starting at the beginning of a blank file. If the file handle represents a physical file that already exists, then the old file is replaced by the new information. (Be careful!) In append mode, the file handle is positioned initially at the end of the file, just before the end-of-file character. Then new data is added to the end of the file without changing whatever was previously in the file. (boolean) fclose( $fileHandle ) Close a previously opened file pointed to by a file handle. Example using fopen() and fclose(): $inFile = " dataFile.dat " ; $in = fopen($inFile, 'r'); $out = fopen( " outputFile.dat " , 'w'); For another example, see the last code example in Section 4.3.

14 4. Summary of Selected PHP Language Elements

(string) fgets($ fileHandle [ , (int) $length ]) Return a string of up to $length -1 bytes from the file pointed to by $fileHandle. If the optional length parameter is not provided, fgets() will read to the end of the line. Examples: $line = fgets($in, 128); $theWholeLine = fgets($in); Text files created on one system may cause problems when using fgets() on a different system. UNIX-based files use only a single character, \n, as a line terminator. Windows systems use two characters, \r\n, as a line terminator. As a result, it is possible that fgets() used in a script running on a Windows computer may not properly detect end-of- line marks in a file created on a UNIX system. (int) fprintf( $fileHandle , (string) {format string} [, {one or more arguments to be displayed} ]) Write a text string according to the format conversion specifier, to the file pointed to by $fileHandle. fprintf() returns an integer value equal to the number of characters written to $fileHandle. Typically, the return value is not needed. The format string is usually specified as a string literal, but may be assigned to a variable prior to calling fprintf(). This capability allows for script-controlled formatting. Examples: fprintf("Here is some output.\n"); // Writes the text into the file. $formatString = "%f, %f, %f\n"; fprintf( $fileHandle ,$formatString,$A,$B,$C); // comma-delimited output The ability to include commas in the output format string means that it is easy to create a comma-delimited file that can be opened directly in a spreadsheet. For Excel, these files typically have a .csv extension. On Windows systems, lines written to a text file, but not necessarily to a

16 4. Summary of Selected PHP Language Elements

$month , $year , $hour , $min , $sec ); } ?>

Document 4.8 (formatExample.php) <?php $a =67; $b =.000717; $c =-67; $d =83.17; $e = "Display a string." ; printf ( "\t%c\n\r%e\n\r%f" , $a , $b , $b ); // no line feeds! printf ( "

%s
%e
%f
"
, $a , $b , $b ); printf ( "
%d %u
"
, $a , $a ); printf ( "
%d %u
"
, $c , $c ); // note effect of %u! printf ( "
He said, "Let's go!"
"
); printf ( "
Your discount is $%'012.2f
"
, $d ); printf ( "
%'x26s
"
, $e ); ?> C 7.17000e-4 0. 67 7.17000e-

67 67 -67 4294967229 He said, "Let's go!" Your discount is $000000083. xxxxxxxxxDisplay a string.

Note that printf() ignores the \n, \r, and \t characters when it displays results in your browser window because HTML ignores “white space.” This explains the presence of the
tags in the format string. However, fprintf() properly interprets these characters when printing to a file. (mixed) print_r( (mixed $expression) [, bool $return ]) Displays information about the $expression in a readable format. Setting $return to true copies the output into a variable rather than displaying it. Example: <?php $cars = array ( "VW" , "GM" , "BMW" , "Saab" ); print_r ( $cars ); $result = print_r ( $cars , true ); printf ( "
%s"
, $result ); ?> Array ( [0] => VW [1] => GM [2] => BMW [3] => Saab ) Array ( [0] => VW [1] => GM [2] => BMW [3] => Saab ) (string) sprintf( (string) $formatString [, (mixed) $var… ]) Returns a string built according to the format specifier and optional arguments. $formatString is usually given as a string literal, but may be assigned to a variable prior to calling printf(), a capability that allows for script-controlled formatting. (mixed) sscanf( $line , $formatString [, (mixed) $var… ])

Reads a line of text from a file and parses input according to a

specified format string. Without optional $var parameters, output is

used to create an array, the elements of which are determined by the

format string. If $var parameters are included, sscanf() returns

the number of parameters parsed. sscanf() will not read past the

end of line if more format specifiers are provided than there are

Examples: strcasecmp(("Dave","David"); // returns - strcasecmp("DAVID","david"); // returns 0 (int) strcmp( (string) $s1 , (string) $s2 ) Perform a case-sensitive comparison of $s1 and $s. strcmp() returns 0 if $s1 and $s2 are identical, an integer value less than 0 if $s1 is less than $s2 (in the lexical sense), and an integer value greater than 0 if $s1 is greater than $s2. Example: strcmp("david","DAVID"); // returns 1 (int) strlen( $s); Returns the length of string $s. (int) strncasecmp( (string) $s1 , (string) $s2 , (int) $n_char ) Perform a case-insensitive comparison on the first $n_char characters of $s1 and $s. strncasecmp() returns 0 if $s1 and $s2 are identical, an integer value less than 0 if $s1 is less than $s2 (in the lexical sense), and an integer value greater than 0 if $s1 is greater than $s. Examples: strncasecmp("Dave","David", 3); // returns 0 strncasecmp(("Dave","David", 4); // returns - $len = min(strlen( "Dave" ),strlen( "David" )); strncasecmp( "Dave" , "David" ,$len); // compares number of characters contained in shorter string parameter and returns - (int) strncmp( (string) $s1 , (string) $s2 , (int) $n_char )

20 4. Summary of Selected PHP Language Elements

Perform a case-sensitive comparison on the first $n_char characters of $s1 and $s. strncmp() returns 0 if $s1 and $s2 are identical, an integer value less than 0 if $s1 is less than $s2 (in the lexical sense), and an integer value greater than 0 if $s1 is greater than $s. Examples: strncmp("Dave","David", 3); // returns 0 $len = min(strlen( "Dave" ),strlen( "David" )); strncmp( "Dave" , "David" ,$len); // compares number of characters contained in shorter string parameter and returns -

4.4.2 Math Functions

PHP’s math functions return integer or floating point results, with a system-dependent precision that is often about 14 digits. The precision may vary from system to system, but it should be sufficient for all but the most specialized calculations. There are also several pre-defined mathematical constants, which are floating point numbers. Constants and functions are built into PHP, with no need for external libraries.^1 Trigonometric functions always assume input parameters in radians or produce angle outputs in radians. Data types are shown in parentheses, e.g. , (float). Optional arguments are enclosed in square brackets. Constants and built-in math functions are listed in Table 4.5. In this table, “x” (and other arguments, in some cases) always represents a generic variable of the appropriate type. Table 4.5. Math constants and functions. Named Constants Description M_1_PI (^) 1/ π M_2_PI (^) 2/ π M_2_SQRTPI (^) 2/( π1/2) M_E Base of the natural logarithm, e = 2.71828… M_EULER (^) Euler’s constant (1)^ = (^1) C, for example, requires that a math library be linked to a source code file before it is compiled.