You are currently viewing Explicit Type Casting in PHP | Complete Guide
  • Post category:PHP

Explicit Type Casting in PHP | Complete Guide

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

  1. (integer), (int) – converts a given data value to an integer
  2. (double), (float), (real) – converts a given data value to a double
  3. (boolean), (bool) – converts a given data value to boolean
  4. (string) – converts a given data value to a string
  5. (array) – converts a given data value to an array
  6. (object) – converts a given data value to an object
  7. (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

  1. intval(data value) – returns an integer value of a given data value
  2. doubleval(data value) – returns double value of a given data value
  3. boolval(data value) – returns boolean value of a given data value
  4. 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”.

Leave a Reply