settype()Function for Changing or Setting the type of a variable in PHP.
bool settype(mixed $var, string $type);
Possible values for the returned string are: Boolean, integer, double, string, array, object, resource NULL.
Returns TRUE on success or FALSE on failure.
<?php $val1 = "Hi"; //string $val2 = true; //boolean settype($val1, "integer"); /*$val1 is now 0 (integer)*/ settype($val2, "string"); /*$val2 is now "1" (string)*/ echo gettype($val1)." $val1 <br />"; echo gettype($val2)." $val2 <br />"; ?>
In above example we set the value of
After setting value, we change the type of variable
In last 2 statement we display the type of variable using
You can pretend that a variable or value is of a different type by using a type cast.
This feature works identically to the way it works in C. You simply put the temporary type in parentheses in front of the variable you want to cast.
For example, you could have declared the two variables from the preceding section using a cast:
$num1 = 50; $num2 = (float) $num1;
The second line means "Take the value stored in
$num1, interpret it as a float, and store it in
$num2 variable will be of type float.
The cast variable does not change types, so
$num1 remains of type integer.
<?php $num1 = 50; /* $num1 integer */ $num2 = (float) $num1; /* $num2 float */ echo gettype($num1)." $num1 <br />"; echo gettype($num2)." $num2 <br />"; ?>