Type Conversions in PHP
last modified June 3, 2025
In the article we explore PHP's type conversion system, covering automatic conversions, explicit casting, and commonly used conversion functions.
PHP is a dynamically typed language, meaning variables do not have fixed types. It automatically converts values between types as needed, a process known as type juggling.
Since PHP determines a variable's type based on its assigned value, it offers great flexibility. However, this dynamic behavior can sometimes lead to unexpected results if types are not carefully managed. For instance, a variable can hold a string initially and later be assigned an integer without causing errors. While convenient, this can create issues in scenarios where a variable's type is critical, such as arithmetic operations or comparisons.
PHP Type Conversion Overview
PHP supports several types: integers, floats, strings, booleans, arrays, and objects. Type conversion allows you to convert between these types as needed.
Conversion Type | Description | Example |
---|---|---|
Type Juggling | Automatic conversion in expressions | $sum = "5" + 2; // int(7) |
Type Casting | Explicit conversion using casting | $int = (int) "123"; |
settype() |
Change variable's type | settype($var, "float"); |
Conversion Functions | Specialized conversion functions | $num = intval("42"); |
The table summarizes the main ways to convert types in PHP. Type juggling
occurs automatically in expressions, while type casting allows explicit
conversion. The settype()
function changes a variable's type, and
conversion functions like intval()
provide specialized
conversions.
Type Juggling (Automatic Conversion)
PHP automatically converts types in expressions based on context. This is called type juggling.
<?php // String to number conversion $sum = "10" + 5; // int(15) echo gettype($sum) . ": " . $sum . "\n"; // Boolean conversion $result = "hello" == true; // bool(true) var_dump($result); // String concatenation $concat = 5 . " items"; // string(7) "5 items" echo $concat . "\n"; // Float to int in array key $arr = [3.5 => "value"]; echo array_key_first($arr); // int(3)
PHP automatically converts types in these common situations:
- Strings to numbers in arithmetic operations
- Values to boolean in comparisons
- Numbers to strings in concatenation
- Floats to integers when used as array keys
$ php type_juggling.php integer: 15 bool(true) 5 items 3
Explicit Type Casting
PHP provides several ways to explicitly convert between types using casting operators.
<?php // String to integer $int = (int) "123"; echo "int: " . $int . "\n"; // Float to integer (truncates) $truncated = (int) 3.99; echo "truncated: " . $truncated . "\n"; // Integer to boolean $bool = (bool) 1; var_dump($bool); // Array to string $str = (string) [1, 2]; echo "array as string: " . $str . "\n"; // Available cast types: // (int), (integer) - to integer // (bool), (boolean) - to boolean // (float), (double), (real) - to float // (string) - to string // (array) - to array // (object) - to object // (unset) - to NULL (deprecated)
Casting is useful when you need to ensure a specific type for a variable or function parameter. Note that some casts like array-to-string produce standardized results ("Array") rather than converting the content.
$ php casting.php int: 123 truncated: 3 bool(true) array as string: Array
Conversion Functions
PHP provides specialized functions for type conversion with additional control.
<?php // String to number conversion $num = intval("42 items"); // 42 $float = floatval("3.14"); // 3.14 // Base conversion $hex = hexdec("FF"); // 255 $bin = bindec("1010"); // 10 // Type setting $var = "123.45"; settype($var, "float"); // String representation $str = strval(123); echo "intval: " . $num . "\n"; echo "hexdec: " . $hex . "\n"; echo "settype: " . gettype($var) . "\n";
These functions provide more control than simple casting:
intval
,floatval
- Convert strings to numbershexdec
,bindec
- Convert from different basessettype
- Change a variable's typestrval
- Get string representation
$ php conversion_functions.php intval: 42 hexdec: 255 settype: double
String to Number Conversion
PHP can convert strings to numbers automatically in arithmetic operations, or
you can use explicit casting and functions like intval
and
floatval
for more control. This is useful when parsing user input
or working with data from external sources.
<?php // Automatic in arithmetic $sum = "10" + 5; // 15 // Explicit with casting $num = (int) "123"; // Using intval() with base $hex = intval("FF", 16); // 255 // Float conversion $price = floatval("19.99"); echo "sum: $sum, num: $num, hex: $hex, price: $price\n";
Number to String Conversion
Numbers can be converted to strings automatically during concatenation, or
explicitly using casting or formatting functions like sprintf
.
This is helpful for displaying numbers in output or building dynamic strings.
<?php // Automatic in concatenation $str = "Value: " . 42; // Explicit casting $strNum = (string) 123; // Formatted conversion $formatted = sprintf("%.2f", 3.14159); echo "$str\n$strNum\n$formatted\n";
Boolean Conversion Rules
PHP has specific rules for converting values to boolean. Values like
false
, 0
, 0.0
, ""
,
"0"
, empty arrays, and null
are considered
false
; all other values are true
. Understanding these
rules is important for writing correct conditional logic.
<?php // Values that evaluate to false: // false, 0, 0.0, "", "0", [], null $trueValues = [1, "hello", [1], true]; $falseValues = [0, "", null, []]; foreach ($trueValues as $val) { echo "$val is " . ($val ? "true" : "false") . "\n"; }
The above code demonstrates how different values evaluate to true or false in
PHP. This is crucial for understanding how conditions work in control structures
like if
statements.
Type Checking Functions
Type checking functions help you verify a variable's type before performing conversions or operations. This can prevent errors and make your code more robust, especially when handling user input or dynamic data.
Function | Description | Example |
---|---|---|
is_int |
Check if integer | is_int(42) |
is_float |
Check if float | is_float(3.14) |
is_numeric |
Check if number or numeric string | is_numeric("123") |
is_string |
Check if string | is_string("text") |
is_array |
Check if array | is_array([]) |
is_bool |
Check if boolean | is_bool(true) |
The above functions allow you to check a variable's type before performing operations or conversions. This is especially useful when dealing with user input or data from external sources, where types may not be guaranteed.
Strict Type Comparisons
For strict type checking, use ===
instead of ==
:
<?php // Loose comparison (type juggling) if (0 == "0") { // true echo "Loose match\n"; } // Strict comparison (type and value) if (0 === "0") { // false echo "This won't print\n"; } else { echo "Strict mismatch\n"; }
The ===
operator checks both value and type, while ==
performs type juggling before comparison.
Source
PHP Manual: Type Juggling
PHP Manual: Type Conversion
Understanding PHP's type conversion system is essential for writing robust code. While type juggling is convenient, being explicit with casting and strict comparisons can prevent subtle bugs.
Author
List all PHP tutorials.