Dynamic Web Pages with PHP Week 3

The material for this week's lecture comes from two different tutorials on-line. I got the first half of the material from php.net (see http://www.php.net/operators.comparison for example) and got the second half of the material from www.webcheats.com (see http://www.webcheatsheet.com/PHP/if_else_switch.php for example). Both of these resources show an index of topics in a left-hand column within the pages. Use these resources to hyperlink between topics. I will be adding comments to this page here as I think about the lecture. Hope you are reviewing it and last week's lecture often until you feel comfortable with the content.

Assignment Operators

The basic assignment operator is "=". Your first inclination might be to think of this as "equal to". Don't. It really means that the left operand gets set to the value of the expression on the rights (that is, "gets set to").

The value of an assignment expression is the value assigned. That is, the value of "$a = 3" is 3. This allows you to do some tricky things:

<?php

$a 
= ($b 4) + 5// $a is equal to 9 now, and $b has been set to 4.
echo $a;

?>

In addition to the basic assignment operator, there are "combined operators" for all of the binary arithmetic, array union and string operators that allow you to use a value in an expression and then set its value to the result of that expression. For example:

<?php

$a 
3;
$a += 5// sets $a to 8, as if we had said: $a = $a + 5;
$b "Hello ";
$b .= "There!"// sets $b to "Hello There!", just like $b = $b . "There!";
echo $b;

?>

Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop. Assignment by reference is also supported, using the $var = &$othervar; syntax. 'Assignment by reference' means that both variables end up pointing at the same data, and nothing is copied anywhere. To learn more about references, please read References explained. As of PHP 5, objects are assigned by reference unless explicitly told otherwise with the new clone keyword.

Comparison Operators

Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables, as they show examples of various type related comparisons.

Comparison Operators
Example Name Result
$a == $b Equal TRUE if $a is equal to $b.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
$a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

If you compare an integer with a string, the string is converted to a number. If you compare two numerical strings, they are compared as integers. These rules also apply to the switch statement.

<?php
var_dump
(== "a"); // 0 == 0 -> true
echo "<br />";
var_dump("1" == "01"); // 1 == 1 -> true
echo "<br />";
var_dump("1" == "1e0"); // 1 == 1 -> true
echo "<br />";

switch ("a") {
case 
0:
    echo 
"0";
    break;
case 
"a"// never reached because "a" is already matched with 0
    
echo "a";
    break;
}
?>

For various types, comparison is done according to the following table (in order).

Comparison with Various Types
Type of Operand 1 Type of Operand 2 Result
null or string string Convert NULL to "", numerical or lexical comparison
bool or null anything Convert to bool, FALSE < TRUE
object object Built-in classes can define its own comparison, different classes are uncomparable, same class - compare properties the same way as arrays (PHP 4), PHP 5 has its own explanation.
string, resource or number string, resource or number Translate strings and resources to numbers, usual math
array array Array with fewer members is smaller, if key from operand 1 is not found in operand 2 then arrays are uncomparable, otherwise - compare value by value (see following example)
array anything array is always greater
object anything object is always greater

Example #1 Transcription of standard array comparison

<?php
// Arrays are compared like this with standard comparison operators
function standard_array_compare($op1$op2)
{
    if (
count($op1) < count($op2)) {
        return -
1// $op1 < $op2
    
} elseif (count($op1) > count($op2)) {
        return 
1// $op1 > $op2
    
}
    foreach (
$op1 as $key => $val) {
        if (!
array_key_exists($key$op2)) {
            return 
null// uncomparable
        
} elseif ($val $op2[$key]) {
            return -
1;
        } elseif (
$val $op2[$key]) {
            return 
1;
        }
    }
    return 
0// $op1 == $op2
}
$result = standard_array_compare(array("Louise"), array("Jeremy"));
echo $result;
?>

See also strcasecmp(), strcmp(), Array operators, and the manual section on Types.

Ternary Operator

Another conditional operator is the "?:" (or ternary) operator.

Example #2 Assigning a default value

<?php
// Example uses of: Ternary Operator

$a = 23;
$b = 12;
$result = ($a > $b) ? ($a - $b) : ($b - $a);
echo $result;

$action = (empty($_POST['action'])) ? 'default' $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    
$action 'default';
} else {
    
$action $_POST['action'];
}

?>
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

Note: Is is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

Example #3 Non-obvious Ternary Behaviour

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true 'true' 'false') ? 't' 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>

Logical Operators

Logical Operators
Example Name Result
$a and $b And TRUE if both $a and $b are TRUE.
$a or $b Or TRUE if either $a or $b is TRUE.
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
! $a Not TRUE if $a is not TRUE.
$a && $b And TRUE if both $a and $b are TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.

The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.)

Example #1 Logical operators illustrated

<?php

// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

// "||" has a greater precedence than "or"
$e false || true// $e will be assigned to (false || true) which is true
$f false or true// $f will be assigned to false
var_dump($e$f);

// "&&" has a greater precedence than "and"
$g true && false// $g will be assigned to (true && false) which is false
$h true and false// $h will be assigned to true
echo "<br />";
var_dump($g$h);
echo "<br />";
?>

The above example will output something similar to:

bool(true)
bool(false)
bool(false)
bool(true)


String Operators> <Incrementing/Decrementing Operators

Incrementing/Decrementing Operators

PHP supports C-style pre- and post-increment and decrement operators.

Note: The increment/decrement operators do not affect boolean values. Decrementing NULL values has no effect too, but incrementing them results in 1.

Increment/decrement Operators
Example Name Effect
++$a Pre-increment Increments $a by one, then returns $a.
$a++ Post-increment Returns $a, then increments $a by one.
--$a Pre-decrement Decrements $a by one, then returns $a.
$a-- Post-decrement Returns $a, then decrements $a by one.

Here's a simple example script:

<?php
echo "<h3>Postincrement</h3>";
$a 5;
echo 
"Should be 5: " $a++ . "<br />\n";
echo 
"Should be 6: " $a "<br />\n";

echo 
"<h3>Preincrement</h3>";
$a 5;
echo 
"Should be 6: " . ++$a "<br />\n";
echo 
"Should be 6: " $a "<br />\n";

echo 
"<h3>Postdecrement</h3>";
$a 5;
echo 
"Should be 5: " $a-- . "<br />\n";
echo 
"Should be 4: " $a "<br />\n";

echo 
"<h3>Predecrement</h3>";
$a 5;
echo 
"Should be 4: " . --$a "<br />\n";
echo 
"Should be 4: " $a "<br />\n";
?>

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ). Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.

Example #1 Arithmetic Operations on Character Variables

<?php
$i 
'W';
for (
$n=0$n<6$n++) {
    echo ++
$i "<br/>\n";
}
?>

The above example will output:

X
Y
Z
AA
AB
AC

Incrementing or decrementing booleans has no effect.

Bitwise Operators

Bitwise operators allow you to turn specific bits within an integer on or off. If both the left- and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values.

<?php
echo 12 9// Outputs '5'

echo "12" "9"// Outputs the Backspace character (ascii 8)
                 // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" "hello"// Outputs the ascii values #0 #4 #0 #0 #0
                        // 'a' ^ 'e' = #4

echo "3"// Outputs 1
              // 2 ^ ((int)"3") == 1

echo "2" 3// Outputs 1
              // ((int)"2") ^ 3 == 1
?>

Bitwise Operators
Example Name Result
$a & $b And Bits that are set in both $a and $b are set.
$a | $b Or Bits that are set in either $a or $b are set.
$a ^ $b Xor Bits that are set in $a or $b but not both are set.
~ $a Not Bits that are set in $a are not set, and vice versa.
$a << $b Shift left Shift the bits of $a $b steps to the left (each step means "multiply by two")
$a >> $b Shift right Shift the bits of $a $b steps to the right (each step means "divide by two")
Warning

Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results to number longer than 32 bits.


Conditional Statements

Sometimes when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. Conditional statements are the set of commands used to perform different actions based on different conditions. In this tutorial we will look at two structures: if...else and switch statements. Both perform in saw way the same task.

If ... Else Statement

The If Statement is a way to make decisions based upon the result of a condition. For example, you might have a script that checks if boolean value is true or false, if variable contains number or string value, if an object is empty or populated, etc. The condition can be anything you choose, and you can combine conditions together to make for actions that are more complicated.

Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false. The syntax for If statement looks as follows:

if (condition) {
   statements_1
} else {
   statements_2
}

Condition can be any expression that evaluates to true or false. If condition evaluates to true, statements_1 are executed; otherwise, statements_2 are executed. statement_1 and statement_2 can be any statement, including further nested if statements.

You may also compound the statements using elseif to have multiple conditions tested in sequence. You should use this construction if you want to select one of many sets of lines to execute.

if (condition_1) {
   statement_1
}
[elseif (condition_2) {
   statement_2
}]
...
[elseif (condition_n_1) {
   statement_n_1
}]
[else {
   statement_n
}]

Let's have a look at the examples. The first example decides whether a student has passed an exam with a pass mark of 57:

<?php
$result = 70;

if ($result >= 57) {
    echo "Pass <br />";
}
else {
    echo "Fail <br />";
}
?>

Next example use the elseif variant on the if statement. This allows us to test for other conditions if the first one wasn't true. The program will test each condition in sequence until:

  • It finds one that is true. In this case it executes the code for that condition.
  • It reaches an else statement. In which case it executes the code in the else statement.
  • It reaches the end of the if ... elseif ... else structure. In this case it moves to the next statement after the conditional structure.
<?php
$result = 70;

if ($result >= 75) { 
    echo "Passed: Grade A <br />";
}
elseif ($result >= 60) {
    echo "Passed: Grade B <br />";
}
elseif ($result >= 45) {
    echo "Passed: Grade C <br />";
}
else {
    echo "Failed <br />";
}
?>

Back to top

Switch Statement

Switch statements work the same as if statements. However the difference is that they can check for multiple values. Of course you do the same with multiple if..else statements, but this is not always the best approach.

A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. The syntax for the switch statement as follows:

switch (expression) {
   case label_1:
      statements_1
      [break;]
   case label_2:
      statements_2
      [break;]
   ...
   default:
     statements_n
     [break;]
}

The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements. If no matching label is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. Use break to prevent the code from running into the next case automatically.

Let's consider an example:

<?php
$flower = "rose";

switch ($flower)
{
  case "rose" : 
     echo $flower." costs $2.50";
     break;
  case "daisy" : 
     echo $flower." costs $1.25";
     break;
  case "orchild" : 
     echo $flower." costs $1.50";
     break;
  default : 
     echo "There is no such flower in our shop";
     break;
}
?>

However, in addition to simple equality you can also test the expression for other conditions, such as greater than and less than relationships. The expression you are testing against must be repeated in the case statement. Have a look at the example:

<?php
$myNumber = 5;

switch ($myNumber) {
  case 0:
    echo "Zero is not a valid value.";
    break;
  case $myNumber < 0:
    echo "Negative numbers are not allowed.";
    break;
  default:
    echo "Great! Ready to make calculations.";
    break;
}
?>

If an expression successfully evaluates to the values specified in more than one case statement, only the first one encountered will be executed. Once a match is made, PHP stops looking for more matches.

Back to top

Type conversion rules to Boolean

  1. When converting to Boolean, the following values are considered FALSE:
    • boolean False
    • integer zero (0)
    • double zero (0.0)
    • empty string and string "0"
    • array with no elements
    • object with no elements
    • special value NULL
  2. Every other value is considered TRUE.

Back to top

Looping Statements

In programming it is often necessary to repeat the same block of code a given number of times, or until a certain condition is met. This can be accomplished using looping statements. PHP has two major groups of looping statements: for and while. The For statements are best used when you want to perform a loop a specific number of times. The While statements are best used to perform a loop an undetermined number of times. In addition, you can use the Break and Continue statements within looping statements.

The While Loop

The While statement executes a block of code if and as long as a specified condition evaluates to true. If the condition becomes false, the statements within the loop stop executing and control passes to the statement following the loop. The While loop syntax is as follows:

while (condition)
{
  code to be executed;
}

The block of code associated with the While statement is always enclosed within the { opening and } closing brace symbols to tell PHP clearly which lines of code should be looped through.

While loops are most often used to increment a list where there is no known limit to the number of iterations of the loop. For example:

while (there are still rows to read from a database)
{
   read in a row;
   move to the next row;
}

Let's have a look at the examples. The first example defines a loop that starts with i=0. The loop will continue to run as long as the variable i is less than, or equal to 10. i will increase by 1 each time the loop runs:

<?php
$i=0;
while ($i <= 10) { // Output values from 0 to 10
   echo "The number is ".$i."<br />";
   $i++;
}
?>

Now let's consider a more useful example which creates drop-down lists of days, months and years. You can use this code for registration form, for example.

<?php

$month_array = array( "January", "February", "March", "April", "May", "June",
                      "July", "August", "September", "October", "November", "December");

echo "<select name=\"day\">";
$i = 1;
while ( $i <= 31 ) {
   echo "<option value=".$i.">".$i."</option>";
   $i++;
}
echo "</select>";

echo "<select name=\"month\">";
$i = 0;
while ( $i <= 11 ) {
   echo "<option value=".$i.">".$month_array[$i]."</option>";   
   $i++;
}
echo "</select>";

echo "<select name=\"year\">";
$i = 1900;
while ( $i <= 2007 ) {    
   echo "<option value=".$i.">".$i."</option>";   
   $i++;
}
echo "</select>";

?>

Note: Make sure the condition in a loop eventually becomes false; otherwise, the loop will never terminate.

Back to top

The Do...While Loop

The Do...While statements are similar to While statements, except that the condition is tested at the end of each iteration, rather than at the beginning. This means that the Do...While loop is guaranteed to run at least once. The Do...While loop syntax is as follows:

do
{
   code to be exected;
}
while (condition);

The example below will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than or equal to 10:

<?php
$i = 0;
do {
   echo "The number is ".$i."<br/>";
   $i++;
}
while ($i <= 10);
?>

Back to top

The For Loop

The For statement loop is used when you know how many times you want to execute a statement or a list of statements. For this reason, the For loop is known as a definite loop. The syntax of For loops is a bit more complex, though for loops are often more convenient than While loops. The For loop syntax is as follows: 

for (initialization; condition; increment)
{
   code to be executed;
}

The For statement takes three expressions inside its parentheses, separated by semi-colons. When the For loop executes, the following occurs:

  • The initializing expression is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.
  • The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the For loop terminates.
  • The update expression increment executes.
  • The statements execute, and control returns to step 2.

Have a look at the very simple example that prints out numbers from 0 to 10:

<?php
for ($i=0; $i <= 10; $i++)
{
   echo "The number is ".$i."<br />";
}
?>

Next example generates a multiplication table 2 through 9. Outer loop is responsible for generating a list of dividends, and inner loop will be responsible for generating lists of dividers for each individual number:

<?php
echo "<h1>Multiplication table</h1>";
echo "<table border=2 width=50%";

for ($i = 1; $i <= 9; $i++ ) {   //this is the outer loop
  echo "<tr>";
  echo "<td>".$i."</td>";
 
   for ( $j = 2; $j <= 9; $j++ ) { // inner loop
        echo "<td>".$i * $j."</td>";
    }

   echo "</tr>";
}

echo "</table>";
?>

At last let's consider the example that uses 2 variables. One to add all the numbers from 1 to 10. The other to add only the even numbers.

<?php
$total = 0;
$even = 0;

for ( $x = 1, $y = 1; $x <= 10; $x++, $y++ ) {
  if ( ( $y % 2 ) == 0 ) {
    $even = $even + $y;
  }
  $total = $total + $x;
}

echo "The total sum: ".$total."<br />";
echo "The sum of even values: ".$even;


?>

Back to top

The Foreach Loop

The Foreach loop is a variation of the For loop and allows you to iterate over elements in an array. There are two different versions of the Foreach loop. The Foreach loop syntaxes are as follows:

foreach (array as value)
{
   code to be executed;
}
   
foreach (array as key => value)
{
   code to be executed;
}

The example below demonstrates the Foreach loop that will print the values of the given array:

<?php
$email = array('john.smith@example.com', 'alex@example.com');
foreach ($email as $value) {
   echo "Processing ".$value."<br />";
}
?>

PHP executes the body of the loop once for each element of $email in turn, with $value set to the current element. Elements are processed by their internal order. Looping continues until the Foreach loop reaches the last element or upper bound of the given array.

An alternative form of Foreach loop gives you access to the current key:

<?php
$person = array('name' => 'Andrew', 'age' => 21, 'address' => '77, Lincoln st.');
foreach ($person as $key => $value) {
   echo $key." is ".$value."<br />";
}
?>

In this case, the key for each element is placed in $key and the corresponding value is placed in $value.

The Foreach construct does not operate on the array itself, but rather on a copy of it. During each loop, the value of the variable $value can be manipulated but the original value of the array remains the same.

Back to top

Break and Continue Statements

Sometimes you may want to let the loops start without any condition, and allow the statements inside the brackets to decide when to exit the loop. There are two special statements that can be used inside loops: Break and Continue.

The Break statement terminates the current While or For loop and continues executing the code that follows after the loop (if any). Optionally, you can put a number after the Break keyword indicating how many levels of loop structures to break out of. In this way, a statement buried deep in nested loops can break out of the outermost loop.

Examples below show how to use the Break statement:

<?php
echo "<p><b>Example of using the Break statement:</b></p>";

for ($i=0; $i<=10; $i++) {
   if ($i==3){break;} 
   echo "The number is ".$i;
   echo "<br />";
}

echo "<p><b>One more example of using the Break statement:</b><p>";

$i = 0;
$j = 0;

while ($i < 10) {
  while ($j < 10) {
    if ($j == 5) {break 2;} // breaks out of two while loops
    $j++;
  }
  $i++;
}

echo "The first number is ".$i."<br />";
echo "The second number is ".$j."<br />";
?>

The Continue statement terminates execution of the block of statements in a While or For loop and continues execution of the loop with the next iteration:

<?php
echo "<p><b>Example of using the Continue statement:</b><p>";

for ($i=0; $i<=10; $i++) {
   if (i==3){continue;} 
   echo "The number is ".$i; 
   echo "<br />";
}
?>

Back to top