Information Technology Reference
In-Depth Information
IV
Operators and Control Statements
Continuing the grammar analogy, operators are the verbs that
allow you to do things in scripts. PHP offers a variety of mathe-
matical and logical operators to compare variables. By using them
with PHP's flow control structures, you can write scripts that fol-
low different paths, depending on the value of the variables.
Table 15.1 shows selected PHP operators. The one that causes
the most trouble, in PHP and in other programming languages, is
the = operator. In PHP, = takes an active role; the value of the
variable on the right side is put into the variable on the left. In PHP, = is not a question that returns
true or false; it's an action. (To test whether two variable are equal, you use = = .)
tip
Would you rather not think
about what method was used to
receive data, but just get it from
the server to use in your script?
Use the $_REQUEST superglobal
instead of $_GET or $_POST .
Table 15.1
Selected PHP Operators
Meaning
Operator
Example
Assignment
=
$x = $y
Add
+
$x + $y
Subtract
-
$x - $y
Multiply
*
$x * $y
Divide
/
$x / $y
Calculate the remainder
%
$x % $y
Negation
-
-$x
Increment by 1
++
$x++
Decrement by 1
$x—
Equal to
==
$x == $y
Exactly equal to
===
$x === $y
Less than
<
$x < $y
Greater than
>
$x > $y
Less than or equal to
<=
$x <= $y
Greater than or equal to
>=
$x >= $y
Not equal to
!=
$x != $y
Logical NOT
!
!$x
Logical AND
&&
$x && $y
Logical OR
||
$x || $y
Group
()
($x = 5) && ($y = $z)
In some other languages, = is a test, and variants on the equal sign are used for assignment. Try to
remember that = is an assignment operator, but don't be surprised if you forget sometimes.
In the example below, the script offers a greeting depending on the weather report. It begins
with two variables, $weather and $times , with their respective assignment operators. The first if
Search WWH ::




Custom Search