PHP gettype() Function (With Examples)

In this tutorial, we will learn about the PHP gettype() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP gettype() function

In PHP, we have a library function gettype() to identify the type of data. The function is primarily used to sanity check the type of data being input in a variable. The function can identify the data into the following data types:

Syntax

The syntax of the gettype() function:

gettype($var)

Parameters

The parameters of the gettype() function:

  • $var is a variable containing data that needs to be checked.

Return Value

The return type of this method is string, it returns a data type.

PHP gettype() Function Example 1

<?php
// Creating variables with random datatype
$var1 = 1;
$var2 = 1.1;
$var3 = null;
$var4 = "example";
$var5 = false;

// using gettype() function to
// get the data type of the variable
echo gettype($var1) . "\n";
echo gettype($var2) . "\n";
echo gettype($var3) . "\n";
echo gettype($var4) . "\n";
echo gettype($var5) . "\n";
?>

Output

The output of the above example is:

integer
double
NULL
string
boolean

PHP gettype() Function Example 2

<?php
// creating an array with random datatypes
$arr = [21, 1.99, new stdClass(), "hello, World", false];

// getting the type of each element of array
// foreach  is used to initialize array
// as independent values
foreach ($arr as $value) {
    // getting and printing the type
    echo gettype($value), "\n";
}
?>

Output

The output of the above example is:

integer
double
object
string
boolean

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.