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:
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).
The one string operator is the concatenation operator. Other string
operations are performed with functions/methods, and we'll learn about
those later.
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).
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).
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
}
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
}
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
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 Amount
Commission Rate
under $1000
5%
$1000 or more but less than $2000
7.5%
$2000 or more, but less than $3500
10%
$3500 or more
15%
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: