PHP Data Type Conversion

Datatype conversion is the process of changing the type of the variable from one datatype to another. PHP provides various datatypes and the type conversion can be performed in various methods. Since, PHP is a loosly typed language, it allows variable declaration without specifying its datatype. The datatype of a variable will be the type of the data value initialized to it. So, we can change the datatype of a PHP variable by changing the type of the dat initialized. The following example code will make it clear.

PHP also supports explicit type casting like other programming languages. PHP type casting is similar to that of C language. PHP also provides settype() function to convert the datatype of a variable. In this article, we are going to see type conversion examples for each data type.

PHP Typecasting for Different Datatype

The following example code shows how to do type casting in PHP to convert a variable datatype. It has a $count variable initialized with an integer value. After initialization, I do type casting with various datatype. After each type casting, I have specified the output and the type of the variable using PHP comment line.

PHP Functions to Convert DataType

PHP provides datatype functions to get or set the datatype of a variable or to check whether a variable is a particular datatype. Those functions are gettype(), settype(), is_array(), is_null() and more. The following code uses PHP settype() to change a variables datatype and uses gettype() and print the result to know what data type if the variable contains before and after conversion. I initialized $count variable as string convert it to an integer using PHP settype().