PHP Data Type Conversion

In PHP, variable’s data type is taken depends on the value assigned to it. When this variable is used in some expression where there is an operand of different datatype, then, the type of this variable will automatically be converted at the time of evaluation. For example, If a variable is initialized as string, and used to perform addition with an integer, then it will be taken as integer at the time of evaluation.

If we want to specify the datatype explicitly, we need to convert it after declaration. There are two ways in converting the data type of variable data. One option is type casting as some languages like C, the other way is to use PHP built-in functions. Both are explained in this article as follows.

php_type_conversion

The type casting method is most familiar one to convert the data type and it’s syntax is,

$variable_name = (data_type) $variavle_name

And, another way to change the type of a variable is implemented by PHP built-in function named as settype(). For example,

<?php
$count = "5";
settype($count,'int');
?>

Since $count is initialized with a value enclosed by double quotes, it’s data type is known as String. After executing the second line of above code, it will be an Integer. To confirm it, we can use gettype() method as shown below.

<?php
$count = "5";
echo gettype($count); // output will be 'string'
settype($count,'int');
echo gettype($count); // output will be 'integer'
?>

In later method, type conversion is going to be done in two steps on making a call to the built in function settype() and then the required conversion will take place. Rather, former method will perform type conversion directly by saving the time of calling settype(). So, it is good programming practice to follow the former one for changing the data type.

This PHP code tutorial was published on April 14, 2013.

↑ Back to Top