<<

CSC 342 - Web Technologies, Spring 2017

PHP Review The PHP Tag

PHP source code is typically an HTML document with tags embedded within it:

Anything within the opening and closing php tags is assumed to be PHP code and should be executed by the PHP interpreter Basic Syntax

Statements must end in a semicolon Variables must start with a $ symbol Line comments are denoted by // Block comments are denoted by /* ... */ keywords, classes, functions and user-defined functions are NOT case sensitive variable names ARE case sensitive Simple Example

Hello World

$message

"; ?>

Variable Naming Rules

Must start with a ($) followed by a letter or the underscore character ( ) Can only contain a-z,A-Z,0-9, and Variable names are case sensitive PHP Types

PHP data types: String Number: (Integer and Float) Boolean Array Object NULL PHP is dynamically typed – types of variables do not need to be declared PHP is generally weakly typed – some type conversions are automatic The String Type

The string type represents a sequence of characters Categories of : delimited by single quotes (’...’) interpolated: delimited by double quotes ("...") The escape character is the backslash (\) The dot (.) operator performs string concatenation Multi-line strings

A string can be defined over multiple lines

Heredoc syntax preserves white space Heredoc Syntax Rules

The <<

Operator Description Example + Addition $a + 3 - Subtraction $a - 3 * Multiplication $a * 3 / Division $a / 3 % Modulus $a % 3 ++ Increment ++$a -- Decrement --$a Assignment Operators

Operator Example Equivalent to = $a = 3 $a = 3 += $a += 3 $a = $a + 3 -= $a -= 3 $a = $a - 3 *= $a *= 3 $a = $a * 3 /= $a /= 3 $a = $a / 3 %= $a %= 3 $a = $a % 3 .= $a .= $b $a = $a . $b PHP Implicit Type Coercion

The type of a variable is implicitly converted based on the context in which the variable is used In PHP this is called “Type Juggling”

The gettype function returns a string representation of a variable’s type Explicit Type Casting

(int), (integer) cast to integer (bool), (boolean) cast to boolean (float), (double), (real) cast to float (string) cast to string (array) cast to array (object) cast to object (unset) cast to NULL PHP Constants

Constants are similar to variables, but the value cannot be changed once set Syntax

NAME is the name of the constant and is traditionally upper case VALUE is the value assigned to the constant Checking Syntax

The syntax of a PHP file can be checked on the command line: php -l FILE.php

The -l (lower case L) is short for lint If a syntax error exists, then the error and line number are reported Control Flow

The basis of control flow is the boolean type Relational operators return boolean values Types of relational operators Equality Comparison Logical The PHP Boolean Type

A boolean expresses a truth value (true or false) The constants TRUE and FALSE are boolean literals FALSE is set to the NULL type Type values that are false when converted to booleans: the boolean FALSE the integer 0 the float 0.0 the empty string ”” and the string ”0” an array with zero elements the NULL type Equality & Comparison Operators

Operator Description Example == equal to $a == 3 === identical to $a === 3 != not equal to $a != 3 !== not identical to $a !== 3 > greater than $a > 3 < less than $a < 3 >= greater than or equal to $a >= 3 <= less than or equal to $a <= 3 Logical Operators

Operator Description Example && and $a == 3 && $b == 0 and low-precedence and $a == 3 and $b == 0 || or $a == 3 || $b == 0 or low-precedence or $a == 3 or $b == 0 ! not !($a == $b) xor exclusive or $a xor $b The Equality and Identity Operators

The equality operator (==) does implicit type coercion before the comparison The identity operator (===) prevents implicit type coercion, that is, for two operands to be identical, they must have the same type and value Example: Selection if, else, and elseif switch Iteration

while loops do while loops for loops PHP Arrays

In PHP an array is an ordered map that associates keys with values PHP has two types of arrays Numerically indexed arrays use integers as keys Associative arrays typically use strings as keys Constructing Arrays with Integer Keys push consecutive values to the array using explicit indices Associative Arrays

Associative arrays map keys other than integers to values

If multiple elements are declared with the same key, then only the value of the last element is used Key Casts

A string containing an integer will be cast to an integer A float is cast to an integer A bool is cast to an integer The null value will be cast to an empty string Arrays and objects cannot be used as keys Printing Arrays

The print r function prints a human readable representation of an array An element of an array can be used as a variable for string interpolation purposes echo "

$a[0]

";

If the key is not an integer then the array element must be surrounded by curly braces for string interpolation echo "

${b[’one’]}

"; The array keyword

Arrays can be assigned with the array keyword

$b = array(’one’ => 1, ’two ’ => 2, ’three’ => 3); ?> The foreach loop

The foreach loop can be used to iterate through the values of an array Arrays with integer keys: foreach($a as $element) { echo "

$element

"; }

Associative arrays: foreach($b as $key => $value) { echo "

$key: $value

"; } Multidimensional Arrays

The value of a key can be an array $tic_tac_toe = array( array(’X’, ’ ’, ’O’), array(’O’, ’O’, ’X’), array(’X’, ’O’, ’ ’) ); Some Useful Array Functions

is array checks if a variable is an array type count returns the number of elements in an array sort performs an in-place sort of an array explode converts a string into an array Superglobals

Superglobals are predefined variables that are provided by the PHP environment $ GET: variables passed to the current script via the HTTP GET method $ POST: variables passed to the current script via the HTTP POST method $ COOKIE: variables passed to the current script via HTTP cookies $ SESSION: session variables available to the current script Defining a PHP Function

function function_name([parameter [, ...]]) { // Statements }

A definition starts with the word function Next is the name of the function, which must start with a letter or underscore, followed by any number of letters, numbers, or underscores The parentheses are required Zero or more parameters, separated by commas The return keyword

The return keyword is used to return a value from a function $x

"; function my_max($x, $y) { return ($x > $y) ? $x : $y; } ?> Variable Scope

Local variables are accessible in context in which they are defined Global variables are accessible from all parts of the code Static variables are accessible from the context in which they are defined, but retain their values Assigning Variables in Global Scope

The value of a global variable can be assigned in a function by using the global statement $a

"; f (); echo "

$a

"; function my_max() { global $a; $a = 5; } ?> Static Variable Example

$count

"; $a = 5; } ?> Including and Requiring Files

The include statement includes and evalutes the specified file The include once statement includes and evalutes the specified file only once The require statement is identical to the include statement, but if a failure occurs, the script is halted The require once statement is identical to the include once statement, but if a failure occurs, the script is halted