LearnContact
Lesson 1218 min read

Type Casting

Understand how PHP automatically converts between types and how to explicitly cast values yourself.

Introduction

PHP is a loosely typed language, which means a variable's type is not fixed and can change depending on how it is used. Sometimes PHP converts values between types for you automatically, and sometimes you need to tell PHP explicitly what type you want a value to be. Both processes are forms of type casting.

Understanding when PHP converts types on its own, and when you should do it yourself, will save you from some of the most common and confusing bugs in PHP code.

What You Will Learn
  • The difference between implicit conversion (type juggling) and explicit casting.
  • How to explicitly cast values using (int), (float), (string), (bool), and (array).
  • Why (int)"abc" becomes 0 instead of throwing an error.
  • The exact rules PHP uses to decide if a value is "truthy" or "falsy".

What is Type Casting?

Type casting means converting a value from one data type to another — for example, turning the string "5" into the integer 5. PHP performs this conversion in two ways: implicitly (automatically, behind the scenes) and explicitly (when you request it directly in your code).

Implicit Conversion

PHP automatically converts a value's type when the context requires it, such as during arithmetic.

Explicit Casting

You deliberately convert a value using a cast operator like (int) or (string).

Implicit Type Conversion (Type Juggling)

PHP's "type juggling" happens when an operator expects one type but receives another. Numeric strings are automatically converted to numbers when used in arithmetic, so PHP can figure out what you meant without you writing any extra code.

juggling.php
<?php
    $result = "5" + 3;       // string "5" is converted to int 5
    echo $result;            // 8
    echo gettype($result);   // integer

    $total = "10" . 5;       // int 5 is converted to string "5"
    echo $total;             // "105"
    echo gettype($total);    // string

    $sum = "3.5" + 1;        // numeric string with decimal becomes float
    echo $sum;               // 4.5
?>
Output
8
integer
105
string
4.5

Notice the pattern: the + operator pulls both operands toward numbers, while the . (concatenation) operator pulls both operands toward strings. PHP decides the target type based on the operator being used, not the other way around.

Why It Is Called "Juggling"

The term comes from how a single PHP variable can hold a string in one line and behave like a number in the next, with PHP juggling its type behind the scenes depending on context.

Explicit Type Casting

When you want full control over a value's type instead of relying on PHP to guess, you can cast it explicitly by placing the target type in parentheses directly before the value.

syntax.php
<?php
    $value = "42";

    $asInt    = (int) $value;
    $asFloat  = (float) $value;
    $asString = (string) 42;
    $asBool   = (bool) $value;
    $asArray  = (array) $value;

    var_dump($asInt);
    var_dump($asFloat);
    var_dump($asString);
    var_dump($asBool);
    var_dump($asArray);
?>
Output
int(42)
float(42)
string(2) "42"
bool(true)
array(1) { [0]=> string(2) "42" }
CastAlso Written AsConverts To
(int)(integer)Integer
(float)(double), (real)Floating-point number
(string)String
(bool)(boolean)Boolean
(array)Array

Casting to Integer and Float

Casting to (int) truncates any decimal portion — it does not round. Casting numeric strings works as you would expect, extracting the leading numeric portion of the string.

numbers.php
<?php
    var_dump((int) 9.9);        // int(9) - truncated, not rounded
    var_dump((int) -9.9);      // int(-9)
    var_dump((int) "42");      // int(42)
    var_dump((int) "42.9abc"); // int(42) - stops at the first invalid character
    var_dump((float) "3.14 is pi"); // float(3.14)
?>
Output
int(9)
int(-9)
int(42)
int(42)
float(3.14)

Casting to String

Casting numbers and booleans to (string) is straightforward: numbers become their digit representation, true becomes "1", and false becomes an empty string.

to-string.php
<?php
    $a = (string) 42;     // "42"
    $b = (string) 3.14;   // "3.14"
    $c = (string) true;   // "1"
    $d = (string) false;  // "" (empty string)

    var_dump($a, $b, $c, $d);
?>
Output
string(2) "42"
string(4) "3.14"
string(1) "1"
string(0) ""

Casting to Boolean

This is where type casting matters most for controlling program flow, since if statements and loops constantly evaluate values as booleans behind the scenes. PHP has a strict, memorizable list of values that are considered "falsy" — every other value is "truthy".

The Falsy Values in PHP
  • The integer 0
  • The float 0.0
  • An empty string ""
  • The string "0" (a single zero character!)
  • An empty array []
  • null
boolean.php
<?php
    var_dump((bool) 0);      // false
    var_dump((bool) 0.0);    // false
    var_dump((bool) "");     // false
    var_dump((bool) "0");    // false - a famous gotcha!
    var_dump((bool) []);     // false
    var_dump((bool) null);   // false

    var_dump((bool) "0.0");  // true! "0.0" is NOT the same as "0"
    var_dump((bool) "false"); // true! Any non-empty string other than "0" is truthy
    var_dump((bool) -1);      // true! Any non-zero number, including negatives, is truthy
?>
Output
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
The "0.0" and "false" Traps

Only the exact string "0" is falsy. The strings "0.0", "false", " " (a space), and "no" are all truthy, because PHP only special-cases the single character "0" for historical reasons.

Casting to Array

Casting a non-array scalar value to (array) wraps it in a new array with a single element at index 0. Casting null produces an empty array.

to-array.php
<?php
    $wrapped = (array) "hello";
    $empty   = (array) null;

    print_r($wrapped);
    print_r($empty);
?>
Output
Array
(
    [0] => hello
)
Array
(
)

Common Gotchas

The most surprising thing about PHP's casting rules is how forgiving they are with invalid input — casts almost never throw errors, they just do their best to produce a sensible value.

Watch Out For These
  • (int)"abc" produces 0, not an error — PHP finds no leading digits and defaults to 0.
  • (int)"12abc" produces 12 — PHP reads digits until it hits a non-numeric character.
  • "10" == "1e1" is true under loose comparison, because both are treated as the number 10.
  • Casting a float that is too large for an integer produces an undefined or platform-dependent result.
gotchas.php
<?php
    var_dump((int) "abc");    // int(0)
    var_dump((int) "12abc"); // int(12)
    var_dump((int) "   7");  // int(7) - leading whitespace is ignored
?>
Output
int(0)
int(12)
int(7)

Common Mistakes

Avoid These Mistakes
  • Assuming (int)"abc" throws an exception — it silently becomes 0.
  • Forgetting that the string "0" is falsy but "0.0" and "false" are truthy.
  • Relying on implicit conversion in comparisons instead of casting explicitly when type matters.
  • Confusing (int) casting (truncation) with rounding — (int) 9.9 is 9, not 10.

Best Practices

  • Cast explicitly whenever a value's type genuinely matters, such as before storing user input as a number.
  • Use var_dump() while learning to see exactly what type and value a cast produced.
  • Prefer strict comparison (===) alongside explicit casting rather than relying on loose comparison to "fix" types.
  • Validate input from forms or APIs before casting, since casting never fails — it just silently substitutes a default.

Frequently Asked Questions

Does casting ever throw an error in PHP?

Almost never. PHP casting is designed to always succeed by falling back to a sensible default, such as 0 for an unparseable string cast to int.

What is the difference between (int) and (float) casting?

(int) always produces a whole number by truncating any decimal part, while (float) preserves the decimal portion of the value.

Is settype() the same as casting with parentheses?

settype() achieves the same conversion but modifies the variable in place and returns a boolean, whereas a cast like (int) $x returns a new value without changing the original variable.

Why is "0" falsy but "0.0" truthy?

PHP only special-cases the exact single-character string "0" as falsy for historical reasons; every other non-empty string, including "0.0", is truthy.

Key Takeaways

  • PHP performs implicit type conversion ("type juggling") automatically based on the operator used.
  • Explicit casts use a target type in parentheses: (int), (float), (string), (bool), (array).
  • (int)"abc" becomes 0 rather than throwing an error — casts always try to succeed.
  • The only falsy values in PHP are 0, 0.0, "", "0", [], and null — everything else is truthy.
  • (int) truncates decimals; it does not round.

Summary

Type casting lets you both understand PHP's automatic conversions and take deliberate control over a value's type when it matters. Mastering the falsy-value rules in particular will prevent a huge class of subtle logic bugs.

Lesson 12 Completed
  • You understand implicit type juggling and why "5" + 3 equals 8.
  • You can explicitly cast values using (int), (float), (string), (bool), and (array).
  • You know the exact list of falsy values in PHP.
  • You are ready to explore PHP's operators in depth.
Next Lesson →

Operators