When working with PHP, you often need to determine the type of a variable. This can be useful for debugging, validating input data, or handling variables dynamically. In this article, we will explore several ways to check variable types in PHP.
Using gettype()
The gettype()
function returns the type of a variable as a string.
$var = 123;
echo gettype($var); // Output: integer
Common Return Values of gettype()
- “boolean”
- “integer”
- “double” (used for both float and double)
- “string”
- “array”
- “object”
- “resource”
- “NULL”
- “unknown type”
Using var_dump()
The var_dump()
function outputs the type and value of a variable. It is useful for debugging.
$var = "Hello, world!";
var_dump($var);
// Output: string(13) "Hello, world!"
Using is_*() Functions
PHP provides several is_*()
functions to check the type of a variable. These functions return true
or false
.
$var = 3.14;
if (is_float($var)) {
echo "The variable is a float.";
}
List of Common is_*() Functions
is_bool($var)
– Checks if a variable is a boolean.is_int($var)
– Checks if a variable is an integer.is_float($var)
– Checks if a variable is a float.is_string($var)
– Checks if a variable is a string.is_array($var)
– Checks if a variable is an array.is_object($var)
– Checks if a variable is an object.is_null($var)
– Checks if a variable isNULL
.is_resource($var)
– Checks if a variable is a resource.
Using instanceof for Objects
If you want to check if a variable is an instance of a specific class, use the instanceof
operator.
class Sample {}
$obj = new Sample();
if ($obj instanceof Sample) {
echo "\$obj is an instance of Sample.";
}
Conclusion
There are multiple ways to check variable types in PHP, depending on your needs. For quick debugging, var_dump()
is useful. If you need precise type checking, is_*()
functions or instanceof
are good options. Understanding these methods will help you write more robust PHP code.
コメント