0Pricing
PHP Academy · Lesson

Type Juggling and Type Casting

Understand how PHP automatically converts between types and how to cast manually.

Type Juggling and Type Casting is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Type Juggling?

Type juggling means PHP automatically converts a value's type when an operator or function requires a different type.

This is convenient but can cause subtle bugs if you don't understand the rules.

Juggling in Arithmetic

PHP converts strings to numbers when used in arithmetic context:

<?php
echo '5' + 3;       // 8  — string '5' becomes int 5
echo '5.5' + 1.5;   // 7  — string '5.5' becomes float
echo '5 cats' + 1;  // 6  — leading numeric part used, rest ignored
echo 'cats' + 1;    // 1  — non-numeric string becomes 0

Loose Comparison ==

The == operator compares values after type juggling — this can produce surprising results:

<?php
var_dump(0 == 'a');      // true in PHP 7 (both become 0)
                          // false in PHP 8 (improved rules!)
var_dump('' == false);   // true
var_dump('1' == true);   // true
var_dump(null == false); // true

Strict Comparison ===

Always use === to compare both value and type — no juggling happens:

<?php
var_dump(1 === '1');   // false — different types
var_dump(1 === 1);     // true
var_dump(null === false); // false
var_dump(0 === false); // false

// Rule of thumb: prefer === unless you explicitly need type coercion

Explicit Type Casting

Cast a value to a specific type by prefixing with (type):

<?php
$str = '42.7';

$int   = (int)    $str;  // 42
$float = (float)  $str;  // 42.7
$bool  = (bool)   $str;  // true
$arr   = (array)  $str;  // ['42.7']

echo $int;   // 42
echo $float; // 42.7

settype() Function

settype() changes a variable's type in-place and returns true/false:

<?php
$value = '123';
settype($value, 'integer');

var_dump($value); // int(123)

// Alternative: intval(), floatval(), strval() functions
$n = intval('0xFF', 16); // 255 — parse hex string

String to Number Edge Cases

Key rules when PHP converts strings to numbers:

  • Leading whitespace is ignored: ' 42 ' → 42
  • Non-numeric prefix: 'php8' → 0 (PHP 8 notice)
  • Scientific notation: '1e3' → 1000.0
  • Hexadecimal strings: '0x1A' is NOT auto-converted to int in PHP 7+

Boolean Casting Rules

These values cast to false; everything else is true:

<?php
$falsy = [false, 0, 0.0, '', '0', [], null];

foreach ($falsy as $v) {
    var_dump((bool) $v); // all bool(false)
}

// Careful:
var_dump((bool) '0');   // false — the STRING '0' is falsy!
var_dump((bool) '00');  // true  — only exactly '0' is falsy

intval() with Bases

intval() accepts an optional base parameter for parsing numeric strings:

<?php
echo intval('0b1010', 2);  // 10  — binary
echo intval('077', 8);     // 63  — octal
echo intval('1F', 16);     // 31  — hexadecimal
echo intval('42');         // 42  — decimal (default base 10)

PHP 8 Improved Juggling

PHP 8 fixed some inconsistent type juggling from previous versions:

  • 0 == 'foo' is now false (was true in PHP 7)
  • Comparing numbers to non-numeric strings: the string is not coerced to 0 anymore
  • This makes PHP 8 safer but may break legacy code relying on old behavior

Avoiding Juggling Bugs

Best practices to avoid type juggling surprises:

<?php
declare(strict_types=1);  // enforce types at function boundaries

// Always use === for comparisons
if ($status === 'active') { /* safe */ }

// Cast explicitly before arithmetic
$total = (float) $_POST['price'] * (int) $_POST['qty'];

// Validate with filter_var
$age = filter_var($_POST['age'], FILTER_VALIDATE_INT);
if ($age === false) { /* invalid input */ }

Quick Check

What does (int) '42abc' evaluate to in PHP?

Recap: Type Juggling

What you've learned about PHP type handling:

  • PHP automatically coerces types in operations — this is type juggling
  • == compares after juggling; === is strict (type + value)
  • Cast explicitly with (int), (float), (string), (bool)
  • Use intval(), floatval(), strval() as functional alternatives
  • PHP 8 improved some juggling edge cases
  • Enable strict_types=1 to reduce surprises in your code

Frequently asked questions

Is the “Type Juggling and Type Casting” lesson free?

Yes — the full text of “Type Juggling and Type Casting” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Type Juggling and Type Casting”?

Understand how PHP automatically converts between types and how to cast manually. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Type Juggling and Type Casting” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Declaring Variables in PHP
  2. PHP Data Types Overview
  3. Echo and Print Output
  4. Type Juggling and Type Casting
← Back to PHP Academy