PHP Review

CSC 342 - Web Technologies

The PHP Tag

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

    <?php
      /* PHP code */
    ?>
  • 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

<!DOCTYPE html>
<html>
<head>
  <title>Hello World</title>
</head>
<body>

<?php
$message = "Hello world";
echo "<p>$message</p>";
?>

</body>
</html>

Variable Naming Rules

  • Must start with a dollar sign ($) 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 string

    • literal: 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

    <?php
      $name = "first_name
        last name";
    ?>
  • Heredoc syntax preserves white space

    <?php
      $name = <<<_END
          first_name
          last name
    _END;
    ?>

Heredoc Syntax Rules

  • The <<<TOKEN starts a heredoc

  • The token name is user defined, it typically should be a value not expected to be seen in the string

  • The ending token must be the first thing on the line followed by a semicolon (TOKEN;)

  • There is no need to escape any characters in a heredoc

Arithmetic Operators

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”

    <?php
      $x = "10"; // string
      $y = 3.14; // float
      $z = $x * $y; // float
    ?>
  • 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

    <?php
      define("NAME", "VALUE");
    ?>
  • 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:

    <?php
      $a = "1000" ==  "+1000"; // TRUE
      $b = "1000" === "+1000"; // FALSE
      $a = "1000" !=  "+1000"; // FALSE
      $b = "1000" !== "+1000"; // TRUE
    ?>

Selection

  • if, else, and elseif

    <?php
      if     ($page == "Home")  {/* code */}
      elseif ($page == "About") {/* code */}
      else                      {/* code */}
    ?>
  • switch

    <?php
      switch ($page) {
        case ("Home"):  {/* code */; break;}
        case ("About"): {/* code */; break;}
        default:        {/* code */; break;}
      }
    ?>

Iteration

  • while loops

  • do while loops

  • for loops

    <?php
      for ($count = 1; $count <= 10; ++$count) {
        echo "The count is" . $count . "\n";
      }
    ?>

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

    <?php
      $a[] = "one";
      $a[] = "two";
      $a[] = "three";
    ?>
  • using explicit indices

    <?php
      $a[0] = "one";
      $a[1] = "two";
      $a[2] = "three";
    ?>

Associative Arrays

  • Associative arrays map keys other than integers to values

    <?php
      $b['one'] = 1;
      $b['two'] = 2;
      $b['three'] = 3;
    ?>
  • 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 "<p>$a[0]</p>";
  • If the key is not an integer then the array element must be surrounded by curly braces for string interpolation

    echo "<p>${b['one']}</p>";

The array keyword

  • Arrays can be assigned with the array keyword

    <?php
      $a = array("one", "two", "three");
    
      $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 "<p>$element</p>";
      }
  • Associative arrays:

      foreach($b as $key => $value) {
        echo "<p>$key: $value</p>";
      }

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

    <?php
    $x = my_max(10, 5);
    echo "<p>$x</p>";
    
    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

    <?php
    $a = 10;
    echo "<p>$a</p>";
    f();
    echo "<p>$a</p>";
    
    function my_max() {
        global $a;
        $a = 5;
    }
    ?>

Static Variable Example

<?php
counter();
counter();

function counter() {
    static $count;
    echo "<p>$count</p>";
    $count += 1;
}
?>

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