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 ↗
Type Checking Functions
Section titled “Type Checking Functions”These is_* functions return true or false based on the variable’s type.
is_string() - Check for String
Section titled “is_string() - Check for String”$text = "Hello";$number = 42;
var_dump(is_string($text)); // bool(true)var_dump(is_string($number)); // bool(false)
// Common use case: validate inputfunction 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)is_bool() - Check for Boolean
Section titled “is_bool() - Check for Boolean”$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 booleanvar_dump(is_bool($emptyString)); // bool(false)is_array() - Check for Array
Section titled “is_array() - Check for Array”$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)is_null() - Check for NULL
Section titled “is_null() - Check for NULL”$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)is_numeric() - Check for Numeric Value
Section titled “is_numeric() - Check for Numeric Value”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;}is_object() - Check for Object
Section titled “is_object() - Check for Object”$obj = new stdClass();$array = ['name' => 'John'];
var_dump(is_object($obj)); // bool(true)var_dump(is_object($array)); // bool(false)
// With custom classclass User { public string $name;}
$user = new User();var_dump(is_object($user)); // bool(true)is_callable() - Check if Callable
Section titled “is_callable() - Check if Callable”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 stringvar_dump(is_callable('nonExistent')); // bool(false)
// Check class methodsclass 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)is_resource() - Check for Resource
Section titled “is_resource() - Check for Resource”$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 falseValue Checking Functions
Section titled “Value Checking Functions”These functions check the state or existence of values.
isset() - Check if Set and Not NULL
Section titled “isset() - Check if Set and Not NULL”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 setvar_dump(isset($empty)); // bool(true) - empty string is setvar_dump(isset($null)); // bool(false) - null is not "set"var_dump(isset($undefined)); // bool(false)
// Check multiple variablesvar_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 nullvar_dump(isset($user['phone'])); // bool(false) - key doesn't existempty() - Check if Empty
Section titled “empty() - Check if Empty”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 emptyComparison: isset() vs empty() vs is_null()
Section titled “Comparison: isset() vs empty() vs is_null()”| Value | isset() | empty() | is_null() |
|---|---|---|---|
"hello" | true | false | false |
"" | true | true | false |
0 | true | true | false |
"0" | true | true | false |
null | false | true | true |
false | true | true | false |
[] | true | true | false |
[1, 2] | true | false | false |
| undefined | false | true | error |
// Practical example: form validation$data = ['name' => 'John', 'age' => 0, 'email' => null];
// isset() - good for checking if key exists with non-null valueif (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 nullif (is_null($data['email'])) { echo "Email is specifically null";}Type Information Functions
Section titled “Type Information Functions”gettype() - Get Variable Type
Section titled “gettype() - Get Variable Type”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// objectget_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)Type Conversion Functions
Section titled “Type Conversion Functions”intval() - Convert to Integer
Section titled “intval() - Convert to Integer”echo intval(42); // 42echo intval(4.7); // 4 (truncates, doesn't round)echo intval("42"); // 42echo intval("42abc"); // 42 (stops at non-numeric)echo intval("abc42"); // 0 (starts with non-numeric)echo intval(true); // 1echo intval(false); // 0
// With base parameterecho 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.0echo floatval("3.14"); // 3.14echo floatval("3.14abc"); // 3.14echo floatval("abc3.14"); // 0echo 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.56strval() - Convert to String
Section titled “strval() - Convert to String”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 conversionboolval() - Convert to Boolean
Section titled “boolval() - Convert to Boolean”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)settype() - Set Variable Type In Place
Section titled “settype() - Set Variable Type In Place”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"Type Casting
Section titled “Type Casting”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]Variable Inspection Functions
Section titled “Variable Inspection Functions”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 variablesvar_dump($user['name'], $user['age']);print_r() - Human-Readable Output
Section titled “print_r() - Human-Readable Output”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;var_export() - Valid PHP Code Output
Section titled “var_export() - Valid PHP Code 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 configurationfile_put_contents('config.cache.php', '<?php return ' . var_export($config, true) . ';');Practical Examples
Section titled “Practical Examples”Form Input Validation
Section titled “Form Input Validation”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);}API Response Handling
Section titled “API Response Handling”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'] : [], ];}Type-Safe Function Parameters
Section titled “Type-Safe Function Parameters”/** * 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)Quick Reference Table
Section titled “Quick Reference Table”| Function | Purpose | Returns |
|---|---|---|
is_string($var) | Check if string | bool |
is_int($var) | Check if integer | bool |
is_float($var) | Check if float | bool |
is_bool($var) | Check if boolean | bool |
is_array($var) | Check if array | bool |
is_null($var) | Check if null | bool |
is_numeric($var) | Check if numeric | bool |
is_object($var) | Check if object | bool |
is_callable($var) | Check if callable | bool |
isset($var) | Check if set and not null | bool |
empty($var) | Check if empty | bool |
gettype($var) | Get type name | string |
intval($var) | Convert to int | int |
floatval($var) | Convert to float | float |
strval($var) | Convert to string | string |
boolval($var) | Convert to bool | bool |
settype($var, $type) | Change type in place | bool |