Converting Data Types

Explicit casts

  • (bool), (boolean)
  • (int), (integer)
  • (string)

To boolean

  • In most cases a value will be automatically converted if an operator, function or control structure requires a boolean argument.

Float to integer

  • The number is rounded towards zero.
  • If the float is beyond the bounds of an integer, the result is undefined and no warning is given.
  • Avoid casting an unknown float, as the result will sometimes be unexpected (i.e. the result of "(int) ((0.1+0.7) * 10)" is 7 rather than 8, due to a slight loss of precision).
  • All possible values for a 32-bit int can be represented exactly by a float, since the floating point numbers are generally 64-bits
  • There is no risk of rounding errors when converting a value from an integer to a float and back again to an integer (i.e. (int)($intvar * 1.0)).

Boolean to integer

FALSE --> 0 (zero)
TRUE --> 1 (one)

To float

  • From types other than strings, the conversion is the same as if the value would have been converted to integer and then to float.

To string

  • strval( )
  • String conversion is automatically done in the scope of an expression for you where a string is needed.
123      --> "123"
12.34 --> "12.34"
TRUE --> "1"
FALSE --> "" (empty string)
NULL --> "" (empty string)

ARRAY --> "Array"
OBJECT --> "Object"
RESOURCE --> "Resource id #n"

To array

  • For an integer, float, string, boolean, or resource, you get an array with one element (with index 0).
  • For an object, you get an array of the properties (member variables) of that object; the keys are the names of the member variables.
  • For a NULL value, you get an empty array.

Resources URL: 
notes/php/resources
Sources URL: 
notes/php/sources

See Also