Have an account? Sign in
Login  Register  Facebook
This Page is Under Construction! - If You Want To Help Please Send your CV - Advanced Web Core (BETA)
Quick Table of Contents
[Edit] Adapting Data Types with Type Juggling
Because of PHP’s lax attitude toward type definitions, variables are sometimes automatically cast to best fit the circumstances in which they are referenced. 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
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
September 12, 2011