PHP Type Casting

PHP Type Casting

PHP typecasting refers to changing the variable from one data type to another data type.

PHP Data Type Casting

This is the process of changing a variable's data type to another data type automatically or manually. This process is known as type casting and it can be done in two ways.

  • 1.0 Implicit Casting (Automatic)
  • 2.0 Explicit Casting (Manual)

Implicit Casting

Implicit data typecasting can be done by PHP automatically. Let us understand it with the help of an example. Let us perform the divide operation by two integer numbers then in this case result might be either integer or float number.

Source Code

Try it now

Explicit Casting

Explicit casting can be customized by the user. Users can change variable types from one data type to another data type with the help of PHP methods.

Let us see different casting methods.

Cast Description
(int) or (integer) : Cast to an integer.
(float) or (double) or (real) :Cast to a float.
(bool) or (boolean) : Cast to a boolean.
(string): Cast to a string.
(array): Cast to an array.
(object): Cast to an object.

Casting Of Float To Integer

Simply use (int) or (integer) to cast a variable to an integer. It can remove the decimal part from the float value and make it an integer.

Source Code

Try it now

Casting Of String To Integer.

String data can also be cast into integer using (int) or (integer). This can be used to get numeric data from the forms

Source Code

Try it now

Casting any string that starts with a number followed by a phrase to an integer will return the starting number as an integer.

Source Code

Try it now

Casting To Boolean

To cast any variable into boolean use either bool or boolean.

Source Code

Try it now

Casting To An Array

A single value of the variable can be cast into an array using the array().

Source Code

Try it now

Casting To Float

To cast a variable into float use (float), (double), and (real).

Source Code

Try it now

Casting an integer into float doest does not lose any data loss since an integer doest does not have decimal points.