Explicit Type Casting in PHP
Explicit type casting
If required, programmers can also convert one type of data value to another type; which is known as explicit type casting in PHP. Implicit type casting is another type of casting in PHP
Syntax
(data type keyword) data value;
where: data value can be a literal, variable name, or constant name
Name of the data type keywords for converting data values
- (integer), (int) – converts a given data value to an integer
- (double), (float), (real) – converts a given data value to a double
- (boolean), (bool) – converts a given data value to boolean
- (string) – converts a given data value to a string
- (array) – converts a given data value to an array
- (object) – converts a given data value to an object
- (unset) – converts a given data value to NULL
Example code:
echo (int) 3.142; // 3
echo (double) "3.142; // 3.142
echo (bool) 10; // 1
echo (string) 3.142; // "3.142"
Name of the function for casting data values
- intval(data value) – returns an integer value of a given data value
- doubleval(data value) – returns double value of a given data value
- boolval(data value) – returns boolean value of a given data value
- strval(data value) – returns sting value of a given data value
Example code:
echo intval(3.142); // 3
echo doubleval("3.142"); // 3.142
echo boolval(10) ; // 1
echo strval("3.142"); // 3.142
Converting the type of a variable
- gettype(data value) : string; – returns the type of a given data value
- settype($variablenName,”data type”) : bool; – sets the type of a variable to a given data type
Example code:
$num=10;
echo gettype($num); //integer
echo settype($num, "string");
echo gettype($num); // string
Here, you can convert the type variable from one data type to another type dynamically. In the above code, we have integer 10 in integer type. I want to convert it to string, so we use “settype” function and apply “string”.