Skip to content

Type & Value Functions

PHP provides a comprehensive set of functions for checking variable types, validating values, and converting between types. These functions are essential for writing robust, type-safe code.

PHP Variable Handling Functions - Full Documentation

These is_* functions return true or false based on the variable’s type.

$text = "Hello";
$number = 42;
var_dump(is_string($text)); // bool(true)
var_dump(is_string($number)); // bool(false)
// Common use case: validate input
function processName($name) {
if (!is_string($name)) {
throw new InvalidArgumentException("Name must be a string");
}
return trim($name);
}

is_int() / is_integer() - Check for Integer

Section titled “is_int() / is_integer() - Check for Integer”
$int = 42;
$float = 42.0;
$string = "42";
var_dump(is_int($int)); // bool(true)
var_dump(is_int($float)); // bool(false)
var_dump(is_int($string)); // bool(false)
// Note: is_integer() is an alias for is_int()
var_dump(is_integer($int)); // bool(true)

is_float() / is_double() - Check for Float

Section titled “is_float() / is_double() - Check for Float”
$float = 3.14;
$int = 3;
$string = "3.14";
var_dump(is_float($float)); // bool(true)
var_dump(is_float($int)); // bool(false)
var_dump(is_float($string)); // bool(false)
// Note: is_double() is an alias for is_float()
var_dump(is_double($float)); // bool(true)
$true = true;
$false = false;
$zero = 0;
$emptyString = "";
var_dump(is_bool($true)); // bool(true)
var_dump(is_bool($false)); // bool(true)
var_dump(is_bool($zero)); // bool(false) - 0 is not a boolean
var_dump(is_bool($emptyString)); // bool(false)
$array = [1, 2, 3];
$assoc = ['name' => 'John'];
$string = "not an array";
var_dump(is_array($array)); // bool(true)
var_dump(is_array($assoc)); // bool(true)
var_dump(is_array($string)); // bool(false)
$null = null;
$zero = 0;
$empty = "";
var_dump(is_null($null)); // bool(true)
var_dump(is_null($zero)); // bool(false)
var_dump(is_null($empty)); // bool(false)

This function checks if a variable is a number OR a numeric string.

$int = 42;
$float = 3.14;
$numericString = "42";
$floatString = "3.14";
$text = "hello";
$mixed = "42abc";
var_dump(is_numeric($int)); // bool(true)
var_dump(is_numeric($float)); // bool(true)
var_dump(is_numeric($numericString)); // bool(true)
var_dump(is_numeric($floatString)); // bool(true)
var_dump(is_numeric($text)); // bool(false)
var_dump(is_numeric($mixed)); // bool(false)
// Useful for form validation
$price = $_POST['price'] ?? '';
if (is_numeric($price)) {
$price = (float) $price;
}
$obj = new stdClass();
$array = ['name' => 'John'];
var_dump(is_object($obj)); // bool(true)
var_dump(is_object($array)); // bool(false)
// With custom class
class User {
public string $name;
}
$user = new User();
var_dump(is_object($user)); // bool(true)
function myFunction() {
return "Hello";
}
$closure = function() { return "World"; };
$string = "myFunction";
var_dump(is_callable('myFunction')); // bool(true)
var_dump(is_callable($closure)); // bool(true)
var_dump(is_callable($string)); // bool(true) - function name as string
var_dump(is_callable('nonExistent')); // bool(false)
// Check class methods
class Calculator {
public static function add($a, $b) { return $a + $b; }
public function multiply($a, $b) { return $a * $b; }
}
var_dump(is_callable(['Calculator', 'add'])); // bool(true)
var_dump(is_callable([new Calculator(), 'multiply'])); // bool(true)
$file = fopen('test.txt', 'r');
$string = "not a resource";
var_dump(is_resource($file)); // bool(true)
var_dump(is_resource($string)); // bool(false)
fclose($file);
var_dump(is_resource($file)); // bool(false) - closed resources return false

These functions check the state or existence of values.

Returns true if the variable exists and is not null.

$name = "John";
$age = 0;
$empty = "";
$null = null;
var_dump(isset($name)); // bool(true)
var_dump(isset($age)); // bool(true) - 0 is set
var_dump(isset($empty)); // bool(true) - empty string is set
var_dump(isset($null)); // bool(false) - null is not "set"
var_dump(isset($undefined)); // bool(false)
// Check multiple variables
var_dump(isset($name, $age)); // bool(true) - both are set
// Common use with arrays
$user = ['name' => 'John', 'email' => null];
var_dump(isset($user['name'])); // bool(true)
var_dump(isset($user['email'])); // bool(false) - value is null
var_dump(isset($user['phone'])); // bool(false) - key doesn't exist

Returns true for: "", 0, 0.0, "0", null, false, [], and unset variables.

$values = [
"", // empty string
0, // zero integer
0.0, // zero float
"0", // string zero
null, // null
false, // false
[], // empty array
"hello", // non-empty string
1, // non-zero number
[1, 2], // non-empty array
];
foreach ($values as $value) {
echo var_export($value, true) . " → " . (empty($value) ? "empty" : "not empty") . "\n";
}
// Output:
// '' → empty
// 0 → empty
// 0.0 → empty
// '0' → empty
// NULL → empty
// false → empty
// array() → empty
// 'hello' → not empty
// 1 → not empty
// array(1, 2) → not empty

Comparison: isset() vs empty() vs is_null()

Section titled “Comparison: isset() vs empty() vs is_null()”
Valueisset()empty()is_null()
"hello"truefalsefalse
""truetruefalse
0truetruefalse
"0"truetruefalse
nullfalsetruetrue
falsetruetruefalse
[]truetruefalse
[1, 2]truefalsefalse
undefinedfalsetrueerror
// Practical example: form validation
$data = ['name' => 'John', 'age' => 0, 'email' => null];
// isset() - good for checking if key exists with non-null value
if (isset($data['name'])) {
echo "Name provided: " . $data['name'];
}
// empty() - good for checking if value is "truthy"
if (empty($data['age'])) {
echo "Age is empty or zero"; // This triggers because 0 is empty
}
// is_null() - good for explicitly checking null
if (is_null($data['email'])) {
echo "Email is specifically null";
}

Returns the type as a string.

$values = [
42,
3.14,
"hello",
true,
null,
[1, 2, 3],
new stdClass(),
];
foreach ($values as $value) {
echo gettype($value) . "\n";
}
// Output:
// integer
// double (note: not "float")
// string
// boolean
// NULL
// array
// object

get_debug_type() - Get Readable Type (PHP 8.0+)

Section titled “get_debug_type() - Get Readable Type (PHP 8.0+)”

Returns more specific type information than gettype().

$values = [
42,
3.14,
"hello",
true,
null,
[1, 2, 3],
new stdClass(),
new DateTime(),
];
foreach ($values as $value) {
echo get_debug_type($value) . "\n";
}
// Output:
// int (not "integer")
// float (not "double")
// string
// bool (not "boolean")
// null (lowercase)
// array
// stdClass (class name)
// DateTime (class name)

echo intval(42); // 42
echo intval(4.7); // 4 (truncates, doesn't round)
echo intval("42"); // 42
echo intval("42abc"); // 42 (stops at non-numeric)
echo intval("abc42"); // 0 (starts with non-numeric)
echo intval(true); // 1
echo intval(false); // 0
// With base parameter
echo intval("1A", 16); // 26 (hexadecimal)
echo intval("42", 8); // 34 (octal)
echo intval("101", 2); // 5 (binary)

floatval() / doubleval() - Convert to Float

Section titled “floatval() / doubleval() - Convert to Float”
echo floatval(42); // 42.0
echo floatval("3.14"); // 3.14
echo floatval("3.14abc"); // 3.14
echo floatval("abc3.14"); // 0
echo floatval("1,234.56"); // 1 (comma stops parsing)
// For localized numbers, clean first
$price = "1,234.56";
$cleaned = str_replace(",", "", $price);
echo floatval($cleaned); // 1234.56
echo strval(42); // "42"
echo strval(3.14); // "3.14"
echo strval(true); // "1"
echo strval(false); // "" (empty string)
echo strval(null); // "" (empty string)
// Arrays and objects cannot be directly converted
// strval([1, 2, 3]); // Error: Array to string conversion
var_dump(boolval(1)); // bool(true)
var_dump(boolval(0)); // bool(false)
var_dump(boolval("hello")); // bool(true)
var_dump(boolval("")); // bool(false)
var_dump(boolval("0")); // bool(false)
var_dump(boolval([1, 2])); // bool(true)
var_dump(boolval([])); // bool(false)

Modifies the variable directly and returns success status.

$value = "42";
settype($value, "integer");
var_dump($value); // int(42)
$value = 3.14;
settype($value, "string");
var_dump($value); // string(4) "3.14"
// Valid type strings: "bool", "int", "float", "string", "array", "object", "null"

Direct type conversion using cast operators.

$value = "42.7";
$int = (int) $value; // 42
$float = (float) $value; // 42.7
$string = (string) 42; // "42"
$bool = (bool) $value; // true
$array = (array) $value; // ["42.7"]
// Object casting
$data = ['name' => 'John', 'age' => 30];
$obj = (object) $data;
echo $obj->name; // "John"
// Array from object
$back = (array) $obj;
print_r($back); // ['name' => 'John', 'age' => 30]

Functions for debugging and examining variables.

var_dump() - Detailed Variable Information

Section titled “var_dump() - Detailed Variable Information”

Shows type and value with structure.

$user = [
'name' => 'John',
'age' => 30,
'active' => true,
'roles' => ['admin', 'editor']
];
var_dump($user);
// Output:
// array(4) {
// ["name"]=>
// string(4) "John"
// ["age"]=>
// int(30)
// ["active"]=>
// bool(true)
// ["roles"]=>
// array(2) {
// [0]=>
// string(5) "admin"
// [1]=>
// string(6) "editor"
// }
// }
// Multiple variables
var_dump($user['name'], $user['age']);

Shows structure without type information.

$user = [
'name' => 'John',
'age' => 30,
'roles' => ['admin', 'editor']
];
print_r($user);
// Output:
// Array
// (
// [name] => John
// [age] => 30
// [roles] => Array
// (
// [0] => admin
// [1] => editor
// )
// )
// Return as string instead of printing
$output = print_r($user, true);
echo $output;

Returns a parsable string representation.

$config = [
'debug' => true,
'database' => [
'host' => 'localhost',
'port' => 3306
]
];
var_export($config);
// Output:
// array (
// 'debug' => true,
// 'database' =>
// array (
// 'host' => 'localhost',
// 'port' => 3306,
// ),
// )
// Return as string
$code = var_export($config, true);
// Useful for caching configuration
file_put_contents('config.cache.php', '<?php return ' . var_export($config, true) . ';');

function validateUserInput(array $data): array {
$errors = [];
// Check required fields exist
if (empty($data['name'])) {
$errors['name'] = "Name is required";
} elseif (!is_string($data['name'])) {
$errors['name'] = "Name must be a string";
}
// Validate numeric field
if (!isset($data['age'])) {
$errors['age'] = "Age is required";
} elseif (!is_numeric($data['age'])) {
$errors['age'] = "Age must be a number";
} elseif ((int)$data['age'] < 0 || (int)$data['age'] > 150) {
$errors['age'] = "Age must be between 0 and 150";
}
// Validate email (optional but must be valid if provided)
if (!empty($data['email']) && !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$errors['email'] = "Invalid email format";
}
return $errors;
}
$userData = [
'name' => 'John Doe',
'age' => '25',
'email' => 'john@example.com'
];
$errors = validateUserInput($userData);
if (empty($errors)) {
echo "Validation passed!";
} else {
print_r($errors);
}
function processApiResponse($response): array {
// Ensure we have an array
if (is_string($response)) {
$response = json_decode($response, true);
}
if (!is_array($response)) {
throw new InvalidArgumentException("Invalid response format");
}
// Extract and type-cast data safely
return [
'id' => isset($response['id']) ? (int) $response['id'] : null,
'name' => isset($response['name']) ? (string) $response['name'] : '',
'price' => isset($response['price']) ? (float) $response['price'] : 0.0,
'active' => isset($response['active']) ? (bool) $response['active'] : false,
'tags' => isset($response['tags']) && is_array($response['tags'])
? $response['tags']
: [],
];
}
/**
* Calculate total price with optional discount
*/
function calculateTotal(
int|float $price,
int $quantity = 1,
?float $discount = null
): float {
// Validate at runtime for extra safety
if (!is_numeric($price) || $price < 0) {
throw new InvalidArgumentException("Price must be a positive number");
}
if (!is_int($quantity) || $quantity < 1) {
throw new InvalidArgumentException("Quantity must be a positive integer");
}
$total = $price * $quantity;
if (!is_null($discount) && is_numeric($discount)) {
$total -= $total * ($discount / 100);
}
return round($total, 2);
}
echo calculateTotal(29.99, 3, 10); // 80.97 (10% discount)

FunctionPurposeReturns
is_string($var)Check if stringbool
is_int($var)Check if integerbool
is_float($var)Check if floatbool
is_bool($var)Check if booleanbool
is_array($var)Check if arraybool
is_null($var)Check if nullbool
is_numeric($var)Check if numericbool
is_object($var)Check if objectbool
is_callable($var)Check if callablebool
isset($var)Check if set and not nullbool
empty($var)Check if emptybool
gettype($var)Get type namestring
intval($var)Convert to intint
floatval($var)Convert to floatfloat
strval($var)Convert to stringstring
boolval($var)Convert to boolbool
settype($var, $type)Change type in placebool