Bifalgorithm post · Computer science one · Type Juggling

How does PHP convert numeric strings during arithmetic operations?

How does PHP convert numeric strings during arithmetic operations? (Computer science one · Type Juggling) — "When string values are involved in an arithmetic e…

Ideas in this flowchart

  • PHP type juggling converts string values when they are used in arithmetic expressions.
  • PHP attempts to convert a string variable into a numeric value by parsing it.
  • Parsing proceeds through each numeric character in the string.
  • The resulting numeric type is either an integer or a floating-point number.
  • Parsing stops when the first non-numeric character is encountered.
  • The value parsed before stopping is used in the arithmetic expression.
  • Code Sample 37.3 demonstrates type juggling with arithmetic examples.
  • The string "10" becomes 10, so adding 5 produces 15.
  • The string "3.14" becomes 3.14, so adding 5 produces 8.14.
  • The string "ten" contains no numeric characters, so it becomes zero and the result is 5.
  • The string "10ten" is partially converted to 10, so adding 5 produces 15.
Feed/

How does PHP convert numeric strings during arithmetic operations?

No cover

Channel

Computer science one

1 page

"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"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.