PHP
🔍 PHP gettype() Function
gettype() in PHP is used to determine the exact data type of a variable. In simple terms, it answers the question: “What type of data is this variable holding?”
- What Does gettype() Do? It returns the data type name as a string, helps prevent invalid operations, enables dynamic data inspection, and is widely used during debugging.
🛠️ Basic Usage & Examples
1️⃣ Basic Syntax
Passing a variable into gettype() returns its underlying type name.
$value = 10;
echo gettype($value); // Outputs: integer
2️⃣ Inspecting Different Data Types
Here is how gettype() handles various scalar and complex types:
echo gettype(10); // Outputs: integer
echo gettype(3.14); // Outputs: double
echo gettype("Hello"); // Outputs: string
echo gettype(true); // Outputs: boolean
echo gettype([1, 2, 3]); // Outputs: array
echo gettype(null); // Outputs: NULL
3️⃣ Comparing Similar Values
Even if two variables hold visually similar values, their underlying data types can differ:
$a = "100";
$b = 100;
echo gettype($a); // Outputs: string
echo gettype($b); // Outputs: integer
4️⃣ Using Inside Conditional Statements
You can inspect variables dynamically within functions to route execution logic:
function checkData($data) {
if (gettype($data) == "integer") {
echo "This is a number.";
} else {
echo "This is not an integer.";
}
}
checkData(5); // Outputs: This is a number.
📊 Values Returned by gettype()
The standard string outputs returned by gettype():
integer→ Returns"integer"float→ Returns"double"(Historical note: PHP returns "double" for float values)string→ Returns"string"boolean→ Returns"boolean"array→ Returns"array"object→ Returns"object"null→ Returns"NULL"resource→ Returns"resource"
-
⚡ gettype() vs. is_* Functions
-
For Type Verification: Use
is_*functions (is_int(),is_string(),is_array()) because they are optimized for boolean checks. -
For Inspection & Debugging: Use
gettype()when you need to print or log the variable's type directly.
