home—lects—exams—hws
breeze (snow day)
ch04
Using Numbers
chapter 4
From PHP Visual Quickstart Guide by Larry Ullman
Based on notes by Jack Davis (jcdavis@radford.edu)
- Numeric Operators (functions invoked w/o parentheses):
+,
-,
*,
/ (always floating-point division, not quotient).
- PHP supports assignment operators.
+=,
-=,
*=,
/=,
++,
--.
E.g. $total += 44;
Note that unlike the numeric operators,
the left-hand-side must
of course
be a variable (not any ol' numeric-expression),
just like in other languages1
- Precedence.
Like other languages, PHP has a precedence order for operators.
But to avoid problems with precedence in calculations,
fully2
parenthesize expressions
(just like you should in other languages).
- Some numeric functions:
-
round(4.35) == 4
round(4.289,2) == 4.29
$num = 236.26985;
round ($num) == 236
- ceil rounds to the next higher integer:
ceil(44.3) == returns 45.
floor rounds to the next lower integer:
floor(44.9) == 44.
Note that floor differs from truncation
on negative numbers:
floor(-3.5) == -4.
- Formatting Numbers
-
number_format(428.4959,2) == '428.50'
number_format(428,2) == '428.00'
number_format(123456789) == '123,456,789'
|
number_format can
use two other optional arguments to
indicate symbols for decimal points and
break thousands
can also use
sprintf, printf to provide formats for output numbers
- Random Numbers
echo rand(1,99); // random number in [1,99] (inclusive)
echo rand(); // a random number in [0,getrandmax()]
|
-
The php manual
lists many more math functions that can be used;
we've just reviewed some of the frequently used ones.
- Example:
Form Calculation
- Example:
Random numbers
-
Variable Type Coercion in PHP
1
Well, “just like in other Algol-based syntaxes.”
↩
2
Well, “reasonably fully parenthesize” —
the precedence rules are designed to make
operators like function call, array-lookup, field-lookup etc.
work as expected.
Precedence between arithmetic is not really the purpose.
↩
home—lects—exams—hws
breeze (snow day)