Home Quizzes Leaderboard Competitions Learn Hire Us
About Contact
Log In Sign Up
Learn PHP Variables & Data Types

Variables & Data Types

⏱ 12 min read read
Variables in PHP:

All PHP variables start with a dollar sign $. PHP is dynamically typed
--- you don't declare types, PHP figures them out automatically.

$age = 25; // int

$price = 9.99; // float

$isStudent = true; // bool

$name = "Alice"; // string

$nothing = null; // null

The 4 Core Scalar Types:

int --- whole numbers. PHP int size depends on platform (64-bit on
modern systems).

float --- decimal numbers (also called double).

bool --- true or false (case-insensitive: TRUE, False, etc. all work).

string --- text, in single or double quotes.

String Operations:

$name = "Alice";

strlen($name) // 5

strtoupper($name) // "ALICE"

strtolower($name) // "alice"

str_contains($name, "li") // true (PHP 8+)

substr($name, 1, 3) // "lic"

$name[0] // "A" (first char)

String Interpolation:

Double-quoted strings interpolate variables and escape sequences.

Single-quoted strings are literal --- no variable interpolation, no \n.

$name = "Alice";

$age = 25;

echo "Hello, $name! You are $age."; // interpolated

echo 'Hello, $name!'; // literal: Hello, $name!

echo "Hello, {$name}!"; // curly braces for clarity

IMPORTANT --- Type Juggling:

PHP automatically converts types in comparisons.

"1" == 1 → true (loose comparison, type juggling!)

"1" === 1 → false (strict comparison, type-safe)

ALWAYS use === for comparisons to avoid bugs.

PHP 8 made type juggling stricter but it still exists.

Constants:

Use define() or the const keyword. Constants have no $ prefix.

define('PI', 3.14159);

const MAX_STUDENTS = 30;

echo PI; // 3.14159

echo MAX_STUDENTS; // 30
Code Example
<?php

// PHP detects types automatically

$age = 25;

$price = 9.99;

$isStudent = true;

$name = "Alice";

$nothing = null;

var_dump($age); // int(25)

var_dump($price); // float(9.99)

var_dump($isStudent); // bool(true)

var_dump($name); // string(5) "Alice"

// String operations

echo strlen($name) . "\n"; // 5

echo strtoupper($name) . "\n"; // ALICE

echo substr($name, 1, 3) . "\n"; // lic

// Interpolation --- double quotes only

echo "Hello, $name! Age: $age\n";

// Type juggling --- DANGER

var_dump("1" == 1); // bool(true) --- loose!

var_dump("1" === 1); // bool(false) --- strict, safe!

// Type conversion

$numStr = "42";

$num = (int)$numStr; // string → int

$pi = (float)"3.14"; // string → float

$score = 95;

$msg = "Score: " . (string)$score;

echo $msg . "\n";

// Constants (no $ prefix)

define('PI', 3.14159);

const MAX_STUDENTS = 30;

echo PI . "\n";

echo MAX_STUDENTS . "\n";

// Output:

// Hello, Alice! Age: 25

// Score: 95

// 3.14159

// 30

?>
← Hello, PHP! --- Your First Script Operators & Math →

Log in to track your progress and earn badges as you complete lessons.

Log In to Track Progress