Microsoft Word - Sam's Teach Yourself MySQL in 21 Days - SAMS.doc

(singke) #1
Apart from assigning values, you can also compare. You can use
ƒ == for testing equality
ƒ != for not equal to
ƒ < for smaller than
ƒ <= for smaller than or equal to
ƒ > for greater than
ƒ >= for greater than or equal to
Note Don't confuse = with ==. If you write something like the following:
if ($name = 'John') { echo "Hello John"; }
you will always get "Hello John" output. Why? Because = does an assignment,
not a comparison. Once assigned, $name evaluates to TRUE (because it is not
blank), and the if statement executes the echo statement.

What you probably meant was
if ($name == 'John') { echo "Hello John"; }
which will compare $name with the given string and then decide on the action to
take. If the comparison evaluates to TRUE, the echo statement is executed.

PHP gives you a few shortcuts for assigning variables in a quite compact way. The following are a few
examples:
ƒ $n++ and ++$n increment $n by 1.
ƒ $n-- and --$n decrement $n by 1.
ƒ $n += 6 increments $n by 6.
ƒ $n -= 2.5 decrements $n by 2.5.
ƒ $n /= 10 divides $n by 10.
ƒ $text .= "yours sincerely" appends text to the end of a string called $text.
Note $n++ is a little different from ++$n. If the ++ (or --) is put before the variable, the
incrementing (or decrementing) is done before anything else, such as returning
the value of the expression. If the ++ is put after the variable, the incrementing is
done after returning the value.

Thus
$n = 5; echo $n++;
returns '5' and then sets $n to 6, while
$n = 5; echo ++$n;
sets $n to 6 and then returns '6'.

Operators


PHP has the usual arithmetic operators, including
ƒ + for addition ($x + $y)
ƒ - for subtraction ($subtotal $discount)
ƒ for multiplication ($annual = $monthly 12)
ƒ / for division ($x / 10)
ƒ % for modulo arithmetic ($x % $y gives remainder of $x / $y)


Control Structures: if


PHP offers a number of means of controlling the flow of your script. Look first at conditional control using if
that takes the following form:


if (expression) {
# do this
} elseif (expression) {
# do another thing
} else {
# do something else
}
elseif tests and actions, and else actions are optional. At it's very simplest, you just need if and the
parentheses surrounding the first expression:
Free download pdf