Variables and types

PHP · Essentials · 10 min

Knowing when PHP converts types for you, and when it doesn't, avoids a whole class of subtle bugs.

Variables start with $ and need no declaration: $count = 3;. A variable's type is whatever value it currently holds. The scalar types are int, float, string and bool, plus null for "no value". Use gettype() or get_debug_type() to inspect a value.

PHP converts types in many operations (type juggling). "5" + 3 is 8 because + is numeric. String concatenation uses ., so "5" . 3 is "53".

Comparison is where juggling bites:

  • == compares after conversion: "1" == "01" and 100 == "1e2" are both true.
  • === compares value and type: "1" === 1 is false. Prefer === by default.
  • Since PHP 8, comparing a number with a non-numeric string compares them as strings, so 0 == "abc" is now false (it was true in PHP 7).

Falsy values are false, 0, 0.0, "", "0", null and empty arrays. Note that "0" is falsy but "0.0" and " " are truthy.

The null coalescing operator ?? gives a default when a value is null or undefined: $name = $input ?? 'guest';. Its assignment form is $x ??= []. Constants are declared with const MAX = 10; or define('MAX', 10); and are written without $.

Example

<?php
$count = 3;
$price = 9.5;
$name = "Ada";
$active = true;
$nothing = null;

echo get_debug_type($price), "\n";   // float
echo "5" + 3, "\n";                  // 8
echo "5" . 3, "\n";                  // 53

var_dump("1" == "01");    // bool(true)
var_dump("1" === 1);      // bool(false)
var_dump(0 == "abc");     // bool(false) since PHP 8

$user = $nothing ?? "guest";
echo $user, "\n";                    // guest
const MAX_ITEMS = 10;
echo MAX_ITEMS * 2, "\n";            // 20

Remember

  • Variables start with $ and take the type of their current value
  • Use === unless you really want type juggling
  • ?? supplies a default for null or missing values

Watch out for

  • Treating "0" as truthy: it is one of PHP's falsy values.

Check yourself

  1. What does var_dump("10" == "1e1") print in PHP 8?
  2. Which value is truthy?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.php.net/manual/en/language.types.type-juggling.php