PHP Variables and Data Types Explained — From Zero to Confident
Every website you've ever used stores and moves information around — your username, the price of a product, whether you're logged in or not. PHP is the language running behind the scenes on millions of web servers doing exactly that work. To do any of it, PHP needs a way to hold pieces of information temporarily while it processes them. That's where variables come in. Without them, you couldn't build a login page, a shopping cart, or even a simple 'Hello, [your name]!' greeting.
The problem variables solve is simple: you don't always know the exact value you'll be working with when you write your code. A user's name could be 'Alice' or 'Zhang Wei' or anything in between. Rather than hardcoding a specific value, you use a variable as a placeholder — a named slot that holds whatever value arrives at runtime. Data types tell PHP what kind of value is sitting in that slot, which determines what operations are valid. You can multiply two numbers, but you can't multiply two names — and PHP needs to know the difference.
By the end of this article you'll be able to declare PHP variables with confidence, understand why PHP has eight built-in data types and when each one is appropriate, read and write real PHP code that stores and outputs meaningful data, and spot the beginner mistakes that trip up even developers who've been coding for a while. Let's build this knowledge from the ground up.
Declaring PHP Variables — The Dollar Sign Rule and Naming Your Boxes
In PHP, every variable starts with a dollar sign ($). That's not optional — it's how PHP recognises 'this is a variable, not a keyword or a function name'. Immediately after the dollar sign comes your chosen name. You assign a value using a single equals sign (=), which in programming is called the assignment operator — it doesn't mean 'equal to', it means 'put this value into this box'.
Naming rules matter. Variable names must start with a letter or an underscore, never a number. They're case-sensitive, so $userAge and $userage are two completely different variables — a common source of bugs. Use descriptive names. $a means nothing to the next developer (or future you). $customerAge, $orderTotal, and $isLoggedIn all tell a story at a glance.
PHP is a loosely typed language, which means you don't have to declare what type of data a variable will hold before you use it. You just assign a value and PHP figures out the type automatically. This is very beginner-friendly, but it comes with traps we'll cover in the gotchas section. For now, know that PHP's flexibility is a feature — used carefully.
<?php // Declaring a string variable — text always goes inside quotes $customerName = "Maria Santos"; // Declaring an integer variable — whole numbers, no quotes needed $customerAge = 28; // Declaring a float variable — numbers with decimal points $accountBalance = 1042.75; // Declaring a boolean variable — only two possible values: true or false $isSubscribed = true; // Outputting variables using echo // The dot (.) is PHP's string concatenation operator — it joins strings together echo "Customer: " . $customerName . "\n"; // Prints the customer's name echo "Age: " . $customerAge . "\n"; // Prints the age as text echo "Balance: $" . $accountBalance . "\n"; // Prints the balance echo "Subscribed: "; // Starts the subscribed line echo $isSubscribed ? "Yes" : "No"; // Ternary: prints Yes if true, No if false echo "\n"; // PHP also lets you embed variables directly inside double-quoted strings // This is called variable interpolation — PHP replaces the variable with its value echo "Hello, $customerName! Your balance is $$accountBalance.\n"; // Checking what type PHP assigned using gettype() echo "Type of customerAge: " . gettype($customerAge) . "\n"; // integer echo "Type of accountBalance: " . gettype($accountBalance) . "\n"; // double (PHP calls floats 'double') echo "Type of customerName: " . gettype($customerName) . "\n"; // string ?>
Age: 28
Balance: $1042.75
Subscribed: Yes
Hello, Maria Santos! Your balance is $1042.75.
Type of customerAge: integer
Type of accountBalance: double
Type of customerName: string
PHP's Eight Data Types — What Can You Actually Store?
PHP has eight built-in data types, split into three families. Scalar types hold a single value: strings (text), integers (whole numbers), floats (decimal numbers), and booleans (true/false). Compound types hold multiple values: arrays (ordered lists or key-value maps) and objects (custom structured data). Special types cover two edge cases: NULL (a variable that deliberately holds nothing) and resource (a reference to an external resource like a database connection).
As a beginner you'll spend 90% of your time with the four scalar types and arrays. Objects come into play when you learn object-oriented PHP later. NULL is more common than you'd think — it's the default state of a variable that's been declared but not assigned, and it's also useful for signalling 'no result found'.
Arrays deserve special attention because they're incredibly powerful. An indexed array works like a numbered list — items are stored at positions 0, 1, 2 and so on. An associative array works like a dictionary — each item has a named key ('email', 'age', 'city') that you use to look it up. You'll use arrays constantly in real PHP work: storing database results, handling form submissions, building configuration settings.
<?php // ── SCALAR TYPES ────────────────────────────────────────────── // STRING — any text wrapped in quotes $productName = "Wireless Noise-Cancelling Headphones"; // INTEGER — whole numbers, positive or negative, no decimal point $stockCount = 142; $temperatureInCelsius = -5; // Integers can be negative // FLOAT (also called double) — numbers with a decimal point $productPrice = 89.99; $taxRate = 0.08; // 8% tax stored as a decimal // BOOLEAN — exactly two possible values: true or false (lowercase in PHP) $isInStock = true; $isDiscounted = false; // ── COMPOUND TYPES ──────────────────────────────────────────── // INDEXED ARRAY — like a numbered shopping list, positions start at 0 $shoppingCart = ["Headphones", "Phone Case", "USB Cable"]; // ASSOCIATIVE ARRAY — like a form with labelled fields $customerProfile = [ "firstName" => "James", // key => value "lastName" => "Okonkwo", "email" => "james@example.com", "age" => 34 ]; // ── SPECIAL TYPES ───────────────────────────────────────────── // NULL — the absence of a value; this variable exists but holds nothing $discountCode = null; // ── USING THE DATA ──────────────────────────────────────────── // Calculate final price with tax $finalPrice = $productPrice + ($productPrice * $taxRate); // float arithmetic echo "Product: $productName\n"; echo "Price: $" . number_format($finalPrice, 2) . "\n"; // number_format rounds to 2 decimal places echo "In stock: " . ($isInStock ? "Yes" : "No") . "\n"; echo "Stock count: $stockCount units\n\n"; // Accessing an indexed array by position number echo "First cart item: " . $shoppingCart[0] . "\n"; // Index 0 = first item echo "Second cart item: " . $shoppingCart[1] . "\n"; // Accessing an associative array by key name echo "Customer: " . $customerProfile["firstName"] . " " . $customerProfile["lastName"] . "\n"; echo "Email: " . $customerProfile["email"] . "\n"; // Checking for NULL with is_null() if (is_null($discountCode)) { echo "No discount code applied.\n"; } // var_dump shows type + value — incredibly useful for debugging var_dump($isDiscounted); // Shows: bool(false) var_dump($taxRate); // Shows: float(0.08) ?>
Price: $97.19
In stock: Yes
Stock count: 142 units
First cart item: Headphones
Second cart item: Phone Case
Customer: James Okonkwo
Email: james@example.com
No discount code applied.
bool(false)
float(0.08)
Type Juggling and Type Casting — When PHP Changes Types Behind Your Back
PHP's loosely typed nature means it will sometimes change the type of a value automatically to make an operation work. This is called type juggling or type coercion. For example, if you try to add a number to a string that starts with a number, PHP quietly converts the string to an integer and adds them. This is either magic or madness depending on the situation.
Type casting is when YOU deliberately convert one type to another, using cast operators like (int), (float), (string), or (bool). This puts you in control rather than leaving it to PHP's automatic rules, which are notoriously surprising.
The comparison operator == (double equals) performs type juggling before comparing, which causes famous PHP gotchas like 0 == 'hello' evaluating to true in older PHP versions. The strict comparison operator === (triple equals) checks both value AND type without any conversion. Senior PHP developers use === by default and only reach for == when they specifically want type-flexible comparison. As a beginner, train yourself to use === from day one — it'll save you hours of debugging.
<?php // ── TYPE JUGGLING (PHP does this automatically) ──────────────── $quantityAsString = "5"; // This is a STRING — it has quotes $bonusQuantity = 3; // This is an INTEGER // PHP sees you're adding and converts $quantityAsString to int automatically $totalQuantity = $quantityAsString + $bonusQuantity; echo "Total quantity: $totalQuantity\n"; // Outputs: 8 echo "Type: " . gettype($totalQuantity) . "\n"; // Outputs: integer (PHP juggled the type) // A string that DOESN'T start with a number becomes 0 in arithmetic $nonsenseString = "apples"; $result = $nonsenseString + 10; echo "Nonsense arithmetic result: $result\n"; // Outputs: 10 ("apples" became 0) // ── TYPE CASTING (YOU control the conversion) ───────────────── $rawInput = "42.7 degrees"; // Imagine this came from a form submission $asInteger = (int) $rawInput; // Casts to int — stops at the decimal point $asFloat = (float) $rawInput; // Casts to float — grabs 42.7, ignores " degrees" echo "\nRaw input: $rawInput\n"; echo "Cast to int: $asInteger\n"; // Outputs: 42 echo "Cast to float: $asFloat\n"; // Outputs: 42.7 // Casting to boolean — useful to know what PHP considers 'falsy' $emptyString = (bool) ""; // false — empty string is falsy $zeroValue = (bool) 0; // false — zero is falsy $zeroString = (bool) "0"; // false — the string "0" is ALSO falsy (a classic gotcha!) $nonEmptyStr = (bool) "hello"; // true — any non-empty, non-"0" string is truthy echo "\n--- Boolean casts ---\n"; var_dump($emptyString); // bool(false) var_dump($zeroValue); // bool(false) var_dump($zeroString); // bool(false) ← catches people out! var_dump($nonEmptyStr); // bool(true) // ── LOOSE vs STRICT COMPARISON ──────────────────────────────── $formInput = "10"; // String from a form field $dbValue = 10; // Integer from a database // == (loose): converts types before comparing — both become 10, so true $looseResult = ($formInput == $dbValue); echo "\nLoose comparison (==): " . ($looseResult ? "true" : "false") . "\n"; // true // === (strict): checks type AND value — string vs integer, so false $strictResult = ($formInput === $dbValue); echo "Strict comparison (===): " . ($strictResult ? "true" : "false") . "\n"; // false ?>
Type: integer
Nonsense arithmetic result: 10
Raw input: 42.7 degrees
Cast to int: 42
Cast to float: 42.7
--- Boolean casts ---
bool(false)
bool(false)
bool(false)
bool(true)
Loose comparison (==): true
Strict comparison (===): false
| Data Type | Example Value | Use Case | Falsy When | PHP Type Check Function |
|---|---|---|---|---|
| String | "hello@example.com" | Names, emails, messages, HTML | Empty string "" or "0" | is_string() |
| Integer | 42 or -7 | Counts, IDs, ages, quantities | Value is 0 | is_int() |
| Float | 19.99 or 0.075 | Prices, percentages, coordinates | Value is 0.0 | is_float() |
| Boolean | true or false | Flags, toggles, conditions | Value is false | is_bool() |
| Array | ["a", "b"] or ["key"=>"val"] | Lists, records, config settings | Empty array [] | is_array() |
| NULL | null | Missing data, unset variables | Always falsy | is_null() |
🎯 Key Takeaways
- Every PHP variable starts with $ — this is non-negotiable syntax, not a style choice, and omitting it causes an immediate parse error.
- PHP has four scalar types (string, int, float, bool), two compound types (array, object), and two special types (null, resource) — knowing which to reach for is a core skill.
- Always use === (triple equals) for comparisons by default — == silently converts types before comparing and produces counterintuitive results that are hard to debug.
- The string "0" is falsy in PHP but the string "false" is truthy — PHP's truthiness rules follow strict internal logic, not human intuition, so test edge cases with var_dump().
⚠ Common Mistakes to Avoid
- ✕Mistake 1: Using = instead of == or === in conditions — Writing if ($userAge = 18) instead of if ($userAge === 18) assigns 18 to $userAge and the condition always evaluates as true because 18 is truthy. PHP won't throw an error, making this silent and deadly. Fix: always use == or === for comparisons inside if statements, and consider enabling strict mode with declare(strict_types=1) at the top of your files.
- ✕Mistake 2: Forgetting that array indexes start at 0, not 1 — If you create $colours = ["red", "green", "blue"] and try to access $colours[3], you'll get an 'Undefined array key 3' notice and an empty value, because the last item is at index 2. Fix: remember the rule — the last valid index is always (count of items - 1). Use count($colours) - 1 to get the last index dynamically, or use PHP's end() function to grab the last element safely.
- ✕Mistake 3: Using single quotes when you expect variable interpolation to work — Writing echo 'Hello, $customerName!' will literally print the dollar sign and variable name as text, not the value stored inside it. Single quotes in PHP are completely literal — no variables are evaluated inside them. Fix: switch to double quotes when you want PHP to replace variables with their values: echo "Hello, $customerName!" — or use concatenation: echo 'Hello, ' . $customerName . '!'.
Interview Questions on This Topic
- QWhat is the difference between == and === in PHP, and when would using == instead of === cause a bug in production code?
- QPHP is described as loosely typed — what does that mean exactly, and what is the potential downside of loose typing when handling user-submitted form data?
- QIf a variable is declared as $count = '0', what does var_dump((bool) $count) output, and why does that result matter when writing conditional logic?
Frequently Asked Questions
Do I need to declare a variable type in PHP before using it?
No — PHP is dynamically typed, meaning you just assign a value and PHP automatically determines the type. You can write $score = 100 without ever saying 'this is an integer'. However, if you want to enforce strict types (a good practice in larger projects), add declare(strict_types=1) at the very top of your PHP file before any other code.
What is the difference between null and an empty string in PHP?
An empty string ("") is a valid string value that contains zero characters — the variable exists and holds a string type. null means the variable has no value at all — it holds nothing. They're both falsy in a boolean context, but is_null("") returns false while is_null(null) returns true. Use null to signal 'no data' and empty string to signal 'data was provided but it's blank'.
Why does PHP use a dollar sign ($) for variables?
PHP was designed in the early 1990s and borrowed the $ prefix from Perl, which was the dominant server-side scripting language at the time. It serves a practical purpose — it lets PHP instantly identify variables inside strings for interpolation, and it prevents naming conflicts with built-in PHP keywords. It's purely a language design decision that became part of PHP's identity.
Written and reviewed by senior developers with real-world experience across enterprise, startup and open-source projects. Every article on TheCodeForge is written to be clear, accurate and genuinely useful — not just SEO filler.