Implicit Casting in php

Many operators have expectations of their operands—for instance, binary math operators typically require both operands to be of the same type. PHP’s variables can store integers, floating-point numbers, strings, and more, and to keep as much of the type details away from the programmer as possible, PHP converts values from one type to another as necessary

The conversion of a value from one type to another is called casting. This kind of implicit casting is called type juggling in PHP

Table of Implicit casting rules for binary arithmetic operations

Type of first
operand
Type of second
operand
Conversion performed
IntegerFloating pointThe integer is converted to a floating-point number
IntegerStringThe string is converted to a number; if the value after conversion is a floating point number, the integer is converted to a floating-point number.
Floating pointStringThe string is converted to a floating-point number.
Table of Implicit casting rules for binary arithmetic operations

Some other operators have different expectations of their operands, and thus have different rules. For example, the string concatenation operator converts both operands to strings before concatenating them:

3 . 2.74 // gives the string 32.74

You can use a string anywhere PHP expects a number. The string is presumed to start with an integer or floating-point number. If no number is found at the start of the string, the numeric value of that string is 0. If the string contains a period (.) or upper- or lowercase e, evaluating it numerically produces a floating-point number

For example:

“9 Lives” – 1; // 8 (int)
“3.14 Pies” * 2; // 6.28 (float)
“9 Lives.” – 1; // 8 (float)
“1E3 Points of Light” + 1; // 1001 (float)

Leave a Comment