Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 147 ยท Data Types

Type Juggling and Casting

Learn how PHP converts types automatically, how to cast with (int), (string) and (bool), the PHP 8 comparison changes, and what declare(strict_types=1) does.

PHP is a dynamically typed language: a variable doesn't have a fixed type, and PHP converts values from one type to another when an operation needs it. Add a string to a number and the string becomes a number. Put a number in a string and it becomes text. Use an array in an if and it becomes a boolean. This automatic conversion is called type juggling (or type coercion), and it's one of the reasons PHP is quick to write.

It's also a source of bugs when you don't know the rules. This lesson shows when PHP converts values on its own, how to convert them yourself with casts like (int) and (string), which surprises PHP 8 removed from comparisons, and how declare(strict_types=1); makes function calls stop converting scalar values altogether. You'll see strict_types at the top of most multi-function examples in this tutorial from now on, so it's worth understanding exactly what it does and doesn't do.

This lesson builds on the three previous ones: Strings, Integers and Floats and Booleans and null.

When PHP converts automatically

PHP looks at the context a value is used in and converts it to the type that context needs:

Context Example Converts to
Arithmetic '5' + 3 int or float
String operations 'Total: ' . 42, echo 3.5 string
Conditions if ($items), while ($line) bool
Loose comparison '10' == 10 depends on both sides
Function parameters (default mode) strlen(123) the declared parameter type
PHP Type juggling in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The results:

TEXT
float(13.5)
string(16) "You owe 13.5 EUR"
The cart is not empty
int(5)
int(15)
string(2) "78"

Pay attention to the last two lines. The operator decides the type, not the values: + always means numeric addition, and . always means string concatenation. That's a big advantage over JavaScript, where '7' + '8' gives '78'. In PHP you always know what you'll get from the operator alone.

Explicit casts

To convert a value yourself, write the target type in parentheses before it. This is called a cast:

Cast Result type Function equivalent
(int) int intval($x)
(float) float floatval($x)
(string) string strval($x)
(bool) bool boolval($x)
(array) array none
(object) stdClass object none

Casts never fail with an error: they always produce some value, even if it's meaningless. That makes them handy for data you've already validated, and dangerous for data you haven't. Here are the conversion rules for the four most common targets.

Converting to int and float

PHP Casting strings to numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The rules behind the output:

  • A string is converted from its leading numeric part. Leading whitespace is skipped. '12abc' becomes 12, and a string with no leading number ('abc', '') becomes 0. Casts don't warn about this; arithmetic does (see Integers and Floats).
  • Scientific notation counts: (int) '1e3' is 1000.
  • Hexadecimal strings are not understood: (int) '0x1A' is 0. Use intval($string, 16), or base 0 to detect 0x, 0 and 0b prefixes automatically (intval('012', 0) is 10, read as octal).
  • Floats are truncated toward zero: (int) 9.99 is 9.
  • true becomes 1; false and null become 0.

Converting to string

  • Integers become their digits: (string) 42 is '42'.
  • Floats use up to 14 significant digits, switching to exponent notation for very large or small values: (string) 1.0 is '1', (string) 1e25 is '1.0E+25', (string) 0.00000015 is '1.5E-7'.
  • true becomes '1'; false and null become ''.
  • Arrays can't be converted meaningfully. You get the word 'Array' plus a warning, Array to string conversion, which nearly always means a bug.
  • Objects can only be converted if their class defines __toString() (see Magic Methods); otherwise you get an Error.

Converting to bool

(bool) follows the truthy/falsy table from Booleans and null: false, 0, 0.0, '', '0', [] and null become false, everything else true.

Converting to array

PHP Casting to arrays and objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A scalar becomes a one-element array, null becomes an empty array, and an object becomes an array of its properties. That's why you'll sometimes see foreach ((array) $maybeList as $item): it lets code accept a single value, a list or null. Casting an array to (object) gives a stdClass whose properties are the array's keys.

Only use the short cast names. PHP 8.5 deprecates the long aliases (integer), (boolean), (double) and (binary); they now produce messages like Deprecated: Non-canonical cast (integer) is deprecated, use the (int) cast instead. The old (real) cast was removed in PHP 8.0 and (unset) in PHP 8.0 as well.

settype() and gettype()

settype($var, 'int') converts a variable in place and returns true on success. gettype($var) returns the type's name as a string ('integer', 'double', 'string', ...), with historical names; the newer get_debug_type() returns the names you write in code ('int', 'float'). Casts are more common than settype() because they work in expressions: $page = (int) $input;.

Casting is not validation

A cast always succeeds, which means it can hide garbage. Suppose a URL has ?page=abc. (int) 'abc' gives 0, and your code happily shows page zero. Worse, ?id=5 OR 1=1 becomes 5, which looks fine but means you never noticed someone was probing your site. Validate first, then convert:

PHP Validate before you convert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

filter_var() with FILTER_VALIDATE_INT returns an int for valid integers (it trims surrounding whitespace) and false for anything else, so '12abc', 'abc', '3.5' and '' are all rejected while the cast turns each of them into a plausible-looking number. You'll use filter_var() a lot in Handling Forms and Form Validation. (printf formats are explained in Formatting Strings.)

PHP 8 changed how strings and numbers compare

The loose comparison == juggles types too, and before PHP 8 it did something notorious: when comparing a number with a non-numeric string, it converted the string to a number. Since 'abc' became 0, 0 == 'abc' was true. This caused real security bugs, such as checks where a 0 matched any password hash string.

PHP 8.0 fixed it. Now, when a number meets a string:

  • If the string is numeric (like '42', ' 42' or '1e2'), they're compared as numbers.
  • Otherwise, the number is converted to a string and the two are compared as strings.
PHP String and number comparison in PHP 8

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is false, false, then six true/false values you can check against these rules, and finally bool(false) for the strict comparison:

Expression PHP 7 PHP 8
0 == 'abc' true false
0 == '' true false
'1' == '01' true true
'10' == '1e1' true true
100 == '1e2' true true
'42' == '42 ' false true (trailing whitespace is allowed in numeric strings since 8.0)

The middle rows are still a trap: two numeric strings compare as numbers, so '1' == '01' and '10' == '1e1' are true even though the strings differ. That's why you should compare strings with ===, which checks the type and value with no conversion at all. Comparison Operators covers == versus === in full.

strict_types: no juggling for function arguments

By default, PHP converts scalar arguments to match a function's declared parameter types. A function that wants an int accepts the string '7' and receives 7. This is coercive mode. It's convenient, but it can mask mistakes, so PHP lets each file opt into strict mode with a declaration that must be the very first statement in the file:

PHP
<?php
declare(strict_types=1);

In strict mode, a scalar argument must already have the declared type, or PHP throws a TypeError. There's one exception: an int is accepted where a float is expected, because that conversion never loses information.

PHP Coercive mode (no strict_types)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Without strict types, '3' becomes 3, 42 becomes '42', and 2.0 becomes 2. Only '3 times', which isn't a valid integer, is rejected. (A float with a fractional part, like 2.5, would be accepted with a deprecation notice about losing precision.) Now the same function in strict mode:

PHP Strict mode with declare(strict_types=1)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output:

TEXT
string(6) "ababab"
float(2.5)
TypeError: repeatWord(): Argument #2 ($times) must be of type int, string given, called in main.php on line 18
TypeError: strlen(): Argument #1 ($string) must be of type string, int given
int(8)

Notice three things:

  1. Strict mode applies to built-in functions too: strlen(12345) now fails.
  2. half(5) works: int-to-float widening is the one allowed conversion.
  3. The last line still prints int(8). strict_types only affects function arguments, return values and typed property assignments. Operators like +, . and ==, conditions, and explicit casts keep juggling as usual.

strict_types is decided by the file that makes the call, not the file that defines the function. If a strict file calls a function from a non-strict library, the call is checked strictly. Return types are checked according to the file where the function is defined. Each file opts in separately; the setting never spreads to other files you include.

Most modern PHP projects put declare(strict_types=1); at the top of every file. It turns a whole class of silent bugs into immediate, clear errors, and it forces you to convert input deliberately at the boundary, which is exactly where it belongs. Type Declarations covers the rest of PHP's type system.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does var_dump('5' . 5); print?

    The dot is always string concatenation, so both operands become strings. The operator, not the values, decides the type.
  2. 2. What is (int) '0x1F'?

    Casts don't understand hexadecimal strings. The leading numeric part is just 0. Use intval('0x1F', 16) or intval('0x1F', 0) to get 31.
  3. 3. In PHP 8, what does var_dump(0 == 'hello'); print?

    Since PHP 8.0, a number compared with a non-numeric string is converted to a string, so '0' is compared with 'hello' and they differ. In PHP 7 this was true.
  4. 4. A file starts with declare(strict_types=1);. Which line still works without an error?

    strict_types affects function arguments, return values and typed properties, not operators. The other three pass a value of the wrong scalar type to a built-in function and throw TypeError.
  5. 5. Why is (int) $_GET['id'] not enough to validate an ID?

    Casts never fail, so they hide bad input. Validate with filter_var(..., FILTER_VALIDATE_INT), which returns false for anything that isn't a clean integer.

Summary

  • PHP converts values based on context: arithmetic, strings, conditions, comparisons and function parameters. The operator decides the result type: + is numeric, . is string.
  • Casts are (int), (float), (string), (bool), (array) and (object). The long aliases like (integer) are deprecated in PHP 8.5.
  • String-to-number casts use the leading numeric part, ignore hex, and never fail; float-to-int truncates. Arrays converted to strings give 'Array' and a warning.
  • Casting is not validation: use filter_var() or is_numeric() on input first.
  • PHP 8 compares a number with a non-numeric string as strings, so 0 == 'abc' is false. Numeric strings still compare as numbers ('1' == '01'), so use === for strings.
  • declare(strict_types=1); makes scalar argument, return and property types strict (except int-to-float) for calls made from that file. Operators and casts are unaffected.

Next: Math Functions