Getting Started

Variables and Types

Learn PHP variables, data types, type juggling, and how PHP handles loose typing.

PHP Variables

PHP variables start with a $ sign followed by the variable name. PHP is loosely typed — you don't need to declare variable types.

Data Types

  • String: Text
  • Integer: Whole numbers
  • Float: Decimal numbers
  • Boolean: true or false
  • Array: Ordered map
  • Object: Instance of a class
  • NULL: No value
  • Resource: Reference to external resource

Type Juggling

PHP automatically converts types when needed. This can lead to surprising results — use strict comparison === to avoid issues.

PHP 8 Typed Properties

PHP 8 introduced union types and named arguments for stricter typing.

Example

php
<?php
// String
$name = "Alice";
$greeting = 'Hello, World!';

// Integer
$age = 30;
$negative = -5;

// Float
$price = 19.99;
$pi = 3.14159;

// Boolean
$isAdmin = true;
$isGuest = false;

// NULL
$value = null;

// Checking types
var_dump($age);      // int(30)
var_dump($price);    // float(19.99)
var_dump($name);     // string(5) "Alice"
gettype($age);       // "integer"

// Type juggling
$result = "5" + 3;   // 8 (int)
$concat = "5" . 3;   // "53" (string)

// Loose vs strict comparison
var_dump(0 == "foo");    // true  (loose - dangerous!)
var_dump(0 === "foo");   // false (strict - safe!)

// Type casting
$str = "42.5 miles";
$num = (int) $str;       // 42
$float = (float) $str;   // 42.5
$bool = (bool) "";        // false
$bool2 = (bool) "0";     // false
$bool3 = (bool) "hello"; // true
Try it yourself — PHP