SyntaxStudy
Sign Up
PHP Type Juggling & Casting
PHP Beginner 1 min read

Type Juggling & Casting

Type Juggling & Casting

PHP automatically converts types when needed (type juggling). You can also cast explicitly.

Explicit Casting

  • (int) or intval()
  • (float) or floatval()
  • (string) or strval()
  • (bool) or boolval()
  • (array)

Falsy Values

false, 0, 0.0, "", "0", [], null evaluate to false.

Example
<?php
// Type juggling (automatic)
var_dump(0 == "foo");     // true (old juggling)
var_dump(0 === "foo");    // false (strict)

// PHP 8: changed behaviour
var_dump(0 == "foo");     // false in PHP 8+

// Explicit casting
$str  = "42abc";
$num  = (int)$str;        // 42
$flt  = (float)"3.14px"; // 3.14

// settype
$val = "100";
settype($val, "integer");
var_dump($val);            // int(100)
?>