Prev | Current Page 144 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

Consider the
following snippet:
$total = 5; // an integer
$count = "15"; // a string
$total += $count; // $total = 20 (an integer)
?>
The outcome is the expected one; $total is assigned 20, converting the $count variable
from a string to an integer in the process. Here??™s another example demonstrating
PHP??™s type-juggling capabilities:
$total = "45 fire engines";
$incoming = 10;
$total = $incoming + $total; // $total = 55
?>
CHAPTER 3 ?–  PHP BASICS 71
The integer value at the beginning of the original $total string is used in the
calculation. However, if it begins with anything other than a numerical representation,
the value is 0. Consider another example:
$total = "1.0";
if ($total) echo "We're in positive territory!";
?>
In this example, a string is converted to Boolean type in order to evaluate the if
statement.
Consider one last particularly interesting example. If a string used in a mathematical
calculation includes ., e, or E (representing scientific notation), it will be evaluated as a
float:
$val1 = "1.2e3"; // 1,200
$val2 = 2;
echo $val1 * $val2; // outputs 2400
?>
Type-Related Functions
A few functions are available for both verifying and converting datatypes; they are
covered in this section.
Retrieving Types
The gettype() function returns the type of the variable specified by var. In total, eight
possible return values are available: array, boolean, double, integer, object, resource,
string, and unknown type.


Pages:
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156