Overview of This Lesson

Refresh this page because I am probably still making changes to it.

In this lesson we look at PHP's operators and control structures. You'll find that PHP supports the same knds of arithmetic and logical operators as other languages, and also has if statements and loops. There are a few small differences, and some interesting additions, as you'll see.

Resources

The following references from the PHP Manual will be helpful:

Pre-Requisites

Before going through this tutorial, make sure you've already gone through the Intro to PHP and the Syntax - Variables and Types tutorials.

Operators

Operators in PHP are similar to those in other languages: unary operators, binary operators, and the ternary operator are all supported in PHP. String concatenation is the same but uses a different operator than most other languages. Also, standard operator precedence rules apply in PHP expressions with multiple operators.

Arithmetic Operators

Binary Arithmetic Operators
Operator Description
+ addition
- subtraction
* multiplication
/ division
% modulus
** exponent or "to the power of"

Note that the division operator will always return a float value unless both operands are integers and those two integers are evenly divisible (i.e. if operand1 % operand2 is 0).

Examples:

<p>
  <?php 
    $n1 = 2;
    $n2 = 3;

    $r1 = $n1 + $n2; // 5
    $r2 = $n1 - $n2; // -1
    $r3 = $n1 * $n2; // 6
    $r4 = $n1 / $n2; // 0.66666666666667
    $r5 = $n1 % $n2; // 2
    $r6 = $n1 ** $n2; // 8
  ?>
</p>
Unary Arithmetic Operators
Operator Description
+ identity, also converts string to int or float
- negation
++ pre- or post-incremement
-- pre- or post-decrement
<p>
    <?php 
        $s1 = "5";
        $s2 = "5.2";
        $n1 = 5;
        $n2 = 5.2;
        var_dump(+$s1);  // int (5)
        var_dump(+$s2);  // float (5.2)
        var_dump(-$n2);  // float (-5.2)
        var_dump($n1++); // int (5) 
        var_dump(++$n1);  // int (7)
        var_dump($n2--); // float (5.2)
        var_dump(--$n2);  // float (3.2)
    ?>
    </p>
Arithmetic Assignment Operators
Operator Description
= basic assignment
+= addition assignment
-= subtraction assignment
*= multiplication assignment
/= division assignment
%= modulus assignment
**= exponent assignment

Examples:

<p>
    <?php 
        $n1 = 1;
        $n2 = 2;
        $n1 += $n2;  // assigned itself 1 + 2 = 3
        echo "$n1<br>"; 
        $n1 -= $n2;  // assigned itself 3 - 2 = 1
        echo "$n1<br>";
        $n1 = 2;
        $n1 *= $n2;  // assigned itself 2 * 2 = 4
        echo "$n1<br>";
        $n1 /= $n2;  // assigned itself 4 / 2 = 2
        echo "$n1<br>";
        $n1 %= $n2;  // assigned itself 2 % 2 = 0
        echo "$n1<br>";
        $n1 = 5;
        $n1 **= $n2; // assigned itself 5 ** 2 = 25
        echo "$n1<br>";
    ?>
</p>

String Operators

The one string operator is the concatenation operator. Other string operations are performed with functions/methods, and we'll learn about those later.

String Concatenation
Operator Description
. concatenation
.= concatenation assignment

Examples:

<p>
    <?php 
        $s1 = "Hello";
        $s2 = "World";
        echo $s1.$s2."
"; // HelloWorld $s1 .= " ".$s2; echo $s1; // Hello World ?> </p>

Characters in a String

You probably remember how in Java you can access a single character in a String object using the .charAt(index) method of the String class. You can do this in PHP using a similar function, or by simply using this special syntax:

$stringVar{index}

or you can also use array brackets:

$stringVar[index]

Examples:

<?php
$myString = "Hello, World!";
echo $myString{0}; // prints H
echo $myString[1]; // prints e
echo $myString{12}; // prints !

// the next two statements print a null-string:
echo $myString[24];
echo $myString{25};

// if the index used in the brackets is not valid, "" is returned
?>

Relational and Logical Operators

PHP has the standard set of relational operators, including the ability to test for equality with type coercion and for equality using data type as well as value (similar to JavaScript's == and === operators).

Relational Operators
Operator Description
== equal to, with type coercion
=== identical or exactly equal to
!= not equal to with type coercion, can also use <>
!== not identicial to, inlcuding type
< less than
> greater than
<= less than or equal to
>= greater than or equal to
?: ternary conditional

Example:

<p>
    <?php
        $n1 = 5;
        $n2 = 3;
        $s1 = "5";
        
        var_dump($n1 == $n2); // false
        var_dump($n1 == $s1); // true
        var_dump($n1 === $s1);  // false
        var_dump($n1 != $s1);  // false
        var_dump($n1 !== $s1);  // true
        var_dump($n1 > 5); // false
        var_dump($n1 >= 5);  // true
        var_dump($n1 < 5); // false
        var_dump($n1 <= 5);  // true
        
        var_dump(($n1 == $s1) ? "foo" : "bar"); // foo
                
    ?>
</p>

PHP also supports standard logical operators, including exclusive OR.

Logical Operators
Operator Description
&& or and And
|| or or Or
! Not
xor Exclusive Or

Note that the And and Or operators short circuit (the second expression is never evaluated on an And if the first condition is false or on an Or if the first condition is true).

Examples:

<p>
  <?php
    var_dump(true && true);  // true
    var_dump(true && false);  // false
    var_dump(true || false);  // true
    var_dump(false || false);  // false
    var_dump(false xor false); // false
    var_dump(false xor true); // true 
    
    echo "
"; $n1 = 2; var_dump($n1 > 2 && ++$n1 > 0, $n1); // false, 2 echo "
"; var_dump($n1 >= 2 && ++$n1 < 0, $n1); // false, 3 echo "
"; var_dump($n1 >= 3 || ++$n1 < 0, $n1); // true, 3 echo "
"; var_dump($n1 < 0 || ++$n1 > 2, $n1); // true, 4 ?> </p>

Operator Precedence

As you would expect, PHP follows standard operator precedence rules when evaluating complex expressions.

Control Structures

PHP has if statements and loops just like any other language, and the syntax is similar, if not exactly the same in some instances.

Selections

Note that in all selections, the braces can be left off a block if there is only one statement inside the block.

Single-Sided If

if (condition) {
  // execute if condition is true
}

Example:

<p>
  <?php
    $n1 = 5;
    if ($n1 > 0) {
        echo "$n1 is greater than 0.<br>";
    }
  ?>
</p>

Double-Sided If

if (condition) {
  // execute if condition is true
} else {
  // execute if condition is false
}

Example:

<p>
  <?php
    //$n1 = -5;  // try this too
    if ($n1 > 0) {
        echo "$n1 is greater than 0.
"; } else { echo "$n1 is 0 or less.
"; } ?> </p>

Multi-Sided If

Note that you can write the "else if" as either elseif or else if as long as you're using the braces syntax and not the alternate syntax.

if (condition1) {
    // execute if condition1 is true
} elseif (condition2) {
    // execute if condition2 is true
} elseif (condition3) {
    // execute if condition3 is true
} elseif (condition4) {
    // execute if condition4 is true
} .... 
} else {
    // optional, execute if none are true
}

Example:

<?php 
    $grade = 71;  // try different values
    $gradePoints = 0.0;
    if ($grade >= 80) {
        $gradePoints = 4.0;
    } else if ($grade >= 70) {
        $gradePoints = 3.0;
    } else if ($grade >= 60) {
        $gradePoints = 2.0;
    } else if ($grade >= 50) {
        $gradePoints = 1.0;
    }
    ?>
    <p>Grade Points: <?= $gradePoints ?></p>

Switch

switch (expression) {
    case value1:
        // execute if expression == value1
        break;
    case value2:
        // execute if expression == value2
        break;
    case value3:
        // execute if expression == value3
        break;
    ... 
    default:
        // optional, execute if none of the cases match
}

In the switch statement, the break statement is optional:

swtich (expression) {
    case value1:
        // execute if expression == value1
    case value2:
        // execute if expression == value1 or value2
    case value3:
        // execute if expression == value1, value 2, or value3
        break;
    case value4:
        // execute if expression == value4 only
    ... 
    default:
        // optional, execute if none of the cases match or there's no break;
        //    before we get here
}

Example:

<?php
    $day = "Monday"; // try different values
    $special = "No Special Today";
    switch ($day) {
        case "Sunday":
        case "Saturday":
            $special = "Pizza";
            break;
        case "Monday":
        case "Wednesday":
            $special = "Veggie Samosas";
            break;
        case "Tuesday":
            $special = "Ribs and Wings";
            break;
        case "Thursday";
            $special = "Ravioli";
            break;
        case "Friday":
            $special = "Burgers";
            break;
        default:
            $special = "Invalid Day";
    }
?>
<p>Today's Special: <?= $special ?></p>

Iteration

While Loop

while (condition) {
    // repeat while condition is true
}

Example:

<p>
  <?php
    $max = 10;
    $counter = 0;
    while ($counter < $max) {
        $counter += 2;
        echo "$counter ";
    }
  ?>
</p>

Do While Loop

do {
    // repeat while condition is true
} while (condition);

Example:

<p>
  <?php
    $max = 10;
    $counter = 0;
    do {
        $counter += 2;
        echo "$counter ";
    } while ($counter < $max);
  ?>
</p>

For Loop

for (initExpr; condition; increment) {
    // repeat while condition is true
}

initExpr initializes the loop counter
condition is evaluated at the start of each iteration
increment alters the loop counter and is executed and the end of each iteration

Example:

<p>
  <?php
    $max = 10;
    for ($counter = 2; $counter <= $max; $counter+=2) {
        echo "$counter ";
    }
  ?>
</p>

Exercises

Exercise Set 1: Basic Calculation and Math Functions, Output

For some of these questions, you might wish to have a look through PHP's various Mathmatical Functions.

1. A summation of a series of numbers from 1 to n can be calculated with the formula: (n(n+1))/2

Write a program creates and initializes a variable for n, calculates the summation of the numbers from 1 to n, and then displays the result. For example:

The sum of values from 1 to 10 is 55.

Your output should be enclosed in paragraph or div tags.

2. The volume of a cone with a given radius and height is calculated as
1/3 π radius2 * height

Write a simple program that creates and initializes variables for radius and height, calculates the volume, and displays the area on the screen in the form:

Volume of cone with radius r and height h: vol

Your output should be enclosed in paragraph or div tags. Note that radius, height, and volume are all in bold.

3. Write a simple program that calculates the amount of taxes on a sub total. Create a constant for the HST rate (13%). Create and initialize a variable for the sub total. Calculate the amount of pst and gst on the sub total, and display the total harmonized sales tax (hst). Output and format your example as shown below:

Sub Total: $15.00
PST Amt: $1.20
GST Amt: $0.75
Total HST: $1.95

You can use the number_format() method to format your numeric output.

4. Write a simple program that declares and initializes two variables that represent the lengths of 2 sides of a triangle. Calculate and display the length of the hypotenuse of the triangle.

5. Write a simple program that declares and initializes a variable containing the sub total on a sales receipt at a store. Create a constant called DISCOUNT that contains a discount rate of 10%. Calculate and display the amount of discount on the receipt subtotal and the total amount due. For example, if my sub total was $100, my output would appear as:

Sub Total: $100.00
Discount: $10.00
Total Due: $90.00

Exercise Set 2: Selections

1. Generate a random number between 1 and 100. Display a message if the number generated is evenly divisible by both 3 and 4.

2. Modify the previous program to display a message if the random number is evenly divisible by 3 or evenly divisible by 4.

3. Simulate the tossing of 2 dice: generate 2 random numbers from 1 to 6 and display the results. If the two dice values are the same, display "You win!" otherwise display "You lose!".

4. A program calculates a person's weekly pay based on the following: If the hours worked are less than or equal to 40, the person receives 10 dollars per hour; otherwise, the person receives 10 dollars for the first 40 hours and then 15 dollars for the hours they work over 40. Your program should initialize a variable with the number of hours worked, and then calculate the weekly pay. Display your result.

5. a) Write a program that checks for a valid department number (use a hard-coded variable value). A department number is valid if it is between 1 and 45, inclusive. Display messages stating whether or not the department number is valid.

5. b) Modify the previous question: A valid department number is between 1 and 45 inclusive, or greater than 200.

5. c) Modify the previous question: valid department numbers include department 50, those between 1 and 45 inclusive, and those that are greater than 200.

6. A program needs to display the amount of commission paid to sales people. Commission paid is equal to the amount of sales multiplied by the commission rate. Commission rates are assigned according to the following chart:

Sales AmountCommission Rate
under $10005%
$1000 or more but less than $20007.5%
$2000 or more, but less than $350010%
$3500 or more15%

7. Rewrite the following selection statement as a switch statement:

if ($status == 1) {
    $action = "Phone vendor and request delivery.";
} else if ($status == 2) {
    $action = "Phone customer and warn of late shipment.";
} else if ($status == 3) {
    $action = "Prepare shipping labels.";
} else if ($status == 4)	{
    $action = "Order additional product from vendor.";
} else {
    $action = "Error:  Invalid status code.";
}
echo $action;

8. Write a program that defines and initializes a final grade variable, and give it a value of your choice. Use a multi-sided selection to determine the letter grade for the final grade (according to Sheridan's Grading System). Display the letter grade.

9. Write a program that uses a switch statement to determine the maximum number of days in a month. Initialize a variable for the month number and the 4-digit year. Note that a year is a leap year if it is evenly divisible by 400 or evenly divisble by 4 and not 100.

Exercise Set 3: Iteration

1. Write a simple program that displays the decimal value of 1/2, 1/3, 1/4... 1/25 in the following format:

1/2 = 0.50
1/3 = 0.33
1/4 = 0.25
1/5 = 0.20
....
1/25 = 0.04

Write the program using 3 different kinds of loops: a while loop, do-while loop, and a for-loop.

2. a) Write a program that lists all the numbers between 1 and 100 inclusive that are divisible by both 3 and 4.

2. b) Write a program that lists all the numbers between 1 and 100 that are divisible by 3 or divisible by 4.

3. Write a PHP program that prints a multiplication table for the values from 1 to 12 (use loops):

times tables produced using PHP

4. Generate a random number between 1 and 100. Display a message "This is a prime number." if the number generated is prime.