Concept
How does PHP convert numeric strings during arithmetic operations?
ComputerScienceOne / Type Juggling
"When string values are involved in an arithmetic expression, PHP does something called type juggling. When juggled, an attempt is made to convert a string variable into a numeric value by parsing it. The parsing goes over each numeric character, converting the value to a numeric type (either an integer or floating point number). The first type a non-numeric character is encountered, the parsing stops and the value parsed so far is the value used in the expression. Consider the examples in Code Sample 37.3. In the first segment, $a is type juggled to the value 10, then added to 5, resulting in 15. In the second example, $a represents a floating point number, and is converted to 3.14, the result of adding to 5 is thus 8.14. In the third example, the string does not contain any numerical values. In this case, the parsing stops at the first character and what has been parsed so far is zero! Finally, in the last example, the first two characters in $a are numeric, so the parsing ends at the third character, and what has been parsed so far is 10.\n\n$a = \"10\";\n\n$b = 5 + $a; //b = 15\n\n$a = \"3.14\";\n\n$b = 5 + $a; //b = 8.14\n\n$a = \"ten\";\n\n$b = 5 + $a; //b = 5\n\n//partial conversions also occur:\n\n$a = \"10ten\";\n\n$b = 5 + $a; //b = 15\n\nCode Sample 37.3.: Type Juggling in PHP"
Related Ideas
- How does PHP handle undefined variables, null values, and constants?ComputerScienceOne · Using Variables
- How can PHP read and clean user input from standard input?ComputerScienceOne · Converting Units
- How can strings be used as indices in PHP arrays?ComputerScienceOne · Strings as Indices
- How are variables and variable types handled in PHP?ComputerScienceOne · Entry Point & Command Line Arguments
- What types of values does PHP support?ComputerScienceOne · Using Variables
- How can you compare strings by their content in PHP?ComputerScienceOne · Arrays of Strings
- How do you assign values to variables in PHP?ComputerScienceOne · Using Variables
- What is the order of precedence and associativity of PHP operators?ComputerScienceOne · Order of Precedence