Data Types in PHP
PHP has nine built-in data types. Four of them, int, float, string and bool, hold numbers, text and true or false, and they're called scalar types. PHP works out each value's type as the script runs, and var_dump() shows it. A cast such as (int) converts a value to another type.
Key facts
var_dump("€20")printsstring(5) "€20", because the number counts bytes, and € takes three bytes in UTF-8.- On 64-bit builds of PHP, an int holds whole numbers from -9223372036854775808 to 9223372036854775807.
"10" + 5givesint(15), but"10" . 5givesstring(3) "105".(int) 3.99givesint(3), because a float cast to int drops its fraction instead of rounding.- In PHP 8.5 and 8.6, the casts
(integer),(boolean),(double)and(binary)print a Deprecated notice.
What data types does PHP have?
Every value in PHP has one of nine built-in data types. The type tells PHP what kind of value it's dealing with, such as a whole number or a piece of text, and limits what PHP can do with that value.
You don't write a type when you create a variable. PHP looks at the value and works out the type while the script runs. One variable can hold an int now and a string later. var_dump() shows the type PHP picked.
$name = "Ada";
$age = 36;
$height = 1.65;
$admin = false;
var_dump($name, $age, $height, $admin);string(3) "Ada" int(36) float(1.65) bool(false)
Each output line names the type of one variable and then shows its value.
| Type | What it holds |
|---|---|
int | A whole number, such as 42 or -7 |
float | A number with a decimal point or an exponent, such as 3.14 |
string | A series of bytes, usually text, such as "Hello" |
bool | One of two values, true or false |
null | Only one value, null |
array | A list of values stored under keys, such as [1, 2, 3] |
object | A value built from a class, such as new DateTime() |
callable | A function, or a value that names one, such as "strlen" |
resource | A handle to something outside PHP, such as an open file |
Four of these, int, float, string and bool, are scalar types, and is_scalar() gives true for any of their values. Arrays and objects can hold other values inside them.
A callable such as the string "strlen" names a function that other code can call, and var_dump() shows it as that string. A resource is what a function such as fopen() hands back for an open file. Both come up in later chapters.
Some tutorials count eight types, and others ten. Older editions of the PHP manual listed eight, without callable, and later ten, with callable and iterable. Since PHP 8.2, iterable is an alias for other types rather than a type of its own.
What is the range of an int in PHP?
On 64-bit builds of PHP, an int can be any whole number from -9223372036854775808 to 9223372036854775807. The constants PHP_INT_MIN and PHP_INT_MAX hold those limits, and PHP_INT_SIZE holds the size of an int in bytes.
var_dump(PHP_INT_MIN, PHP_INT_MAX, PHP_INT_SIZE);int(-9223372036854775808) int(9223372036854775807) int(8)
The runner's PHP stores each int in 8 bytes, so PHP_INT_SIZE is 8. If you see the range -2147483648 to 2147483647, it comes from a PHP build that stores ints in 4 bytes, as is usual on 32-bit systems.
With 8-byte ints, 2147483647 + 1 is still an int. Only a result outside the range from PHP_INT_MIN to PHP_INT_MAX turns into a float.
What is null in PHP?
null is the only value of PHP's null type. You can assign it to a variable to show that the variable has no value yet.
$middleName = null;
var_dump($middleName);NULL
var_dump() prints null in capitals, as NULL. Reading a variable that was never assigned also gives null, but PHP prints Warning: Undefined variable first.
How do you check the type of a variable in PHP?
Pass the variable to var_dump() to see its type and value. For the type's name alone, as a string, call get_debug_type(). To test for one type, use one of the is_ functions, such as is_float(), which return true or false.
$price = 4.99;
var_dump($price);
echo get_debug_type($price), "\n";
echo gettype($price), "\n";
var_dump(is_float($price), is_int($price));float(4.99) float double bool(true) bool(false)
get_debug_type() and gettype() return the name instead of printing it, so echo does the printing.
get_debug_type() was added in PHP 8.0 and returns int, float and bool, the same names var_dump() prints for those types. The older gettype() still returns the outdated names integer, double and boolean, and even PHP 8.6 prints no notice for them.
For an object, get_debug_type() returns the class name, such as DateTime, where gettype() only says object.
Which PHP function should you use to see a value's type?
Use var_dump() while you track down a bug, because it shows both the type and the value.
| Function | Result for true, and when to use it |
|---|---|
var_dump() | Prints bool(true). Use it to see what a variable holds. |
print_r() | Prints 1. Use it for a short view of an array. |
gettype() | Returns "boolean". Use it only where older code expects its names. |
get_debug_type() | Returns "bool". Use it to put a type name in a message. |
is_float() | Returns false. Use it to test for one type. |
var_dump() and print_r() print their result, while the other three return a value for your code to use. print_r() prints true as 1 and prints nothing for false or null, so values of different types can look the same.
How do you read var_dump() output in PHP?
Read the type first, then the part in parentheses. For an int, a float or a bool, the parentheses hold the value, and for a string they hold the length, followed by the text in quotes.
var_dump("€20", 4.50, 2.0, 2, null);string(5) "€20" float(4.5) float(2) int(2) NULL
The 5 in string(5) counts bytes, not characters. In UTF-8, the most common way to store text as bytes, the euro sign takes three bytes, so the three characters of €20 take five.
Paste € into the UTF-8 encoder to see its bytes, E2 82 AC. The strings lesson shows how to count characters instead.
Floats print without trailing zeros, so 4.50 shows as float(4.5) and 2.0 as float(2). The type name is what tells float(2) apart from int(2), and NULL has no parentheses at all.
var_dump() prints its output itself and returns nothing, and an echo in front of it adds nothing. It also ends each value with a line break.
Use it instead of echo to inspect a value, because echo can't show you the type.
How does var_dump() show an array in PHP?
For an array, var_dump() prints the number of elements, then each key and value. Square brackets in the code create the array, and arrays get a chapter of their own later in the course.
$user = ["Ada", 36, true];
var_dump($user);
array(3) {
[0]=>
string(3) "Ada"
[1]=>
int(36)
[2]=>
bool(true)
}The numbers in square brackets, [0] to [2], are the keys PHP gave the elements, counting from 0. Each value sits on the line under its key with its own type. This array mixes a string, an int and a bool.
How do you convert a value to another type in PHP?
Write the type you want in parentheses before the value, as in (int) "42". This is called type casting, and the six casts that convert a value are (int), (float), (string), (bool), (array) and (object).
var_dump((int) "42");
var_dump((int) "42abc");
var_dump((int) "abc");
var_dump((int) 3.99);
var_dump((float) "3.14");
var_dump((string) 42);int(42) int(42) int(0) int(3) float(3.14) string(2) "42"
A cast returns a new value and leaves the variable you cast unchanged. PHP follows these rules when it casts.
- A string that starts with a number converts to that number.
"42abc"gives 42, with no warning. - Leading spaces are skipped. A string with no number at the start after that, such as
"abc"or an empty string, gives 0. - A float cast to int loses its fraction, so 3.99 becomes 3 and -3.99 becomes -3. For rounding, use
round(). truebecomes 1 andfalsebecomes 0. As strings, they become"1"and an empty string, andnullbecomes 0 as an int and an empty string as a string.- Since PHP 8.5, casting a float that's too large for an int, such as
(int) 1e20, prints a warning.
The functions intval(), floatval(), strval() and boolval() work like the matching casts. settype($price, "float") converts the variable itself instead of returning a new value.
Which values become false when you cast them to bool in PHP?
PHP treats false, 0, 0.0, -0.0, the empty string, the string "0", an empty array and null as false. Apart from a few special built-in objects, every other value becomes true.
var_dump((bool) "0");
var_dump((bool) "");
var_dump((bool) "0.0");
var_dump((bool) "false");
var_dump((bool) -1);bool(false) bool(false) bool(true) bool(true) bool(true)
The string "0" is false, but "0.0" and "false" are true, because among strings only "0" and the empty string are false. Any number other than zero is true, negative ones included. An if statement tests its condition with these same rules.
What is type juggling in PHP?
Type juggling is PHP converting a value to another type automatically when an operation needs it. Arithmetic operators such as + turn numeric strings into numbers, and the . operator turns numbers into strings.
var_dump("10" + 5);
var_dump("10" . 5);
var_dump("10.5" + 1);
var_dump("3" * "4");int(15) string(3) "105" float(11.5) int(12)
"10" + 5 gives the int 15, because + is an arithmetic operator, while "10" . 5 joins the two as text. When either side of + is a float, or a string that holds one, the result is a float, so "10.5" + 1 gives 11.5.
Juggling doesn't change the variable itself. If $count holds "10", then $total = $count + 5 stores the int 15 in $total, and $count still holds the string "10".
The == operator checks whether two values are equal. It juggles types too, so "10" == 10 is true. A later lesson on comparison operators covers it.
What happens when PHP can't turn a string into a number?
PHP prints a warning or stops with a TypeError, depending on how the string starts. A string that starts with a number but has text after it gives a warning, and PHP still does the math with that number.
var_dump("10 apples" + 5);Warning: A non-numeric value encountered in /app/main.php on line 2 int(15)
A string with no number at the start stops the script with a TypeError, and nothing after that line runs.
var_dump("apples" + 5);
Fatal error: Uncaught TypeError: Unsupported operand types: string + int in /app/main.php:2
Stack trace:
#0 {main}
thrown in /app/main.php on line 2Cast the string first when you know it has text after the number, because (int) "10 apples" gives 10 without a warning. A cast also hides bad input. (int) "apples" quietly gives 0.
$apples = (int) "10 apples";
var_dump($apples + 5);int(15)
Which casts and type functions did PHP 8.5 and 8.6 deprecate?
PHP 8.5 deprecated the cast names (integer), (boolean), (double) and (binary). Deprecated means they still work, but PHP prints a notice and a future version may remove them. Write (int), (bool), (float) and (string) instead, which do the same conversions.
echo "start\n";
var_dump((integer) "5");Deprecated: Non-canonical cast (integer) is deprecated, use the (int) cast instead in /app/main.php on line 3 start int(5)
The notice appears before start, which shows that PHP raises it before running any of the code. The cast still works and gives int(5), and PHP 8.6 prints the same notice as the runner's PHP 8.5.
PHP 8.6 also deprecates four functions named after old type names, is_integer(), is_long(), is_double() and doubleval(). Use is_int(), is_float() and floatval() instead.
The runner's PHP 8.5 doesn't warn about those four functions yet. PHP 8.6 prints a line such as Deprecated: Function is_integer() is deprecated since 8.6, use is_int() instead for each call.
Two older cast names are gone completely. Since PHP 8.0, (real) is a parse error and (unset) stops the script with a fatal error.
Common mistakes with data types in PHP
None of these PHP data type mistakes is a parse error. Most of them start with a string that PHP has to turn into a number or a bool.
- Deprecated: Non-canonical cast (integer) is deprecated. The code uses one of the old cast names that PHP 8.5 deprecated. Write
(int), and use(bool),(float)and(string)for the other three. - Warning: A non-numeric value encountered. A string with text after its number, such as
"10 apples", went into a calculation. Cast it with(int)or(float)first. - Fatal error: Uncaught TypeError: Unsupported operand types: string + int. The string has no number at the start. Check what the variable holds with
var_dump()before the calculation. - bool(true) for the string "false". Every string except
""and"0"casts to true. Writetrueorfalsewithout quotes when you mean a bool.
Exercise
$quantity and $price hold numbers written as strings. Convert $quantity with the (int) cast and $price with the (float) cast, multiply them with *, then pass both and their product to var_dump() so it prints int(3), float(4.5) and float(13.5) on three lines.
$quantity = "3";
$price = "4.50";
var_dump($quantity, $price, $quantity * $price);
int(3) float(4.5) float(13.5)
Show the solution
$quantity = "3";
$price = "4.50";
$quantity = (int) $quantity;
$price = (float) $price;
var_dump($quantity, $price, $quantity * $price);
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this script print?
var_dump("10" + 5);The + operator does arithmetic, so PHP reads "10" as the number 10 and the sum is an int. You only get string(3) "105" from the . operator, which joins values as text.
-
2Which of these strings becomes false when PHP casts it to bool?
Among strings, only "0" and the empty string are false. "0.0" looks like zero, but it is a non-empty string other than "0", so it becomes true, like "false" and a space.
-
3What does this script print?
echo gettype(1.5);gettype() still calls a float double, an older name it hasn't dropped. get_debug_type(1.5) returns float, the name var_dump() uses.
-
4What does this script print?
var_dump((int) 9.99);A cast to int drops the fraction instead of rounding, so 9.99 becomes 9. To get 10, round first, because round(9.99) gives float(10).
-
5Which of these casts makes PHP 8.5 and 8.6 print a deprecation notice?
(integer) is an old alias of (int) that PHP 8.5 deprecated, and the script still runs after the notice. (int), (float) and (string) are the current cast names and print no notice.























