What are the gettype() and settype() functions in PHP ?

Data types are the foundation of programming languages. They are how languages understand what exactly they have to do with particular data. These languages have built-in mechanisms that enforce different treatments of data based on their type.

Data types in PHP

In PHP there are about eight data types. They include:

  • Integer
  • String
  • Float
  • Boolean
  • Array
  • Object
  • Null
  • Resources

You may want to know the type of data, or change the data of a particular type to another type for some purpose. If you want to have control over your data in PHP, two functions could help you do that very well.

  1. gettype() function
  2. settype() function

gettype() function

The gettype() function returns the data type of the variable passed to it as an argument. It can get the type of any variable. To see it, you have to save the return value in a variable and echo it to the screen.

Code

<?php
$ini = 3;
echo gettype($ini) ."<br>";
$mini = 3.2;
echo gettype($mini) ."<br>";
$dini = "Hello";
echo gettype($dini) ."<br>";
$bini = array();
echo gettype($bini) ."<br>";
$gini = array("red", "green", "blue");
echo gettype($gini) ."<br>";
$tini = NULL;
echo gettype($tini) ."<br>";
$zini = false;
echo gettype($zini) ."<br>";
?>

settype() function

The settype() function is used to change the type of a variable from its current type to a specified type. It accepts two parameters. First, the name of the variable to be converted, and second, the type to be converted to.

Code

<?php
$ini = 3;
settype($ini,'string');
echo gettype($ini)."<br>";
$mini = 3.2;
settype($mini,'integer');
echo gettype($mini) . "<br>";
$dini = "Hello people";
settype($dini,'array');
var_dump($dini);
echo"<br>";
echo gettype($dini) . "<br>";
$gini = array("red", "green", "blue");
settype($gini,'string');
echo gettype($gini) . ";";
?>

When using these functions, just be sure of what you want to achieve and how any of the functions will help you do so.

Free Resources