Skip to main content
    Courses/PHP/Variables & Data Types

    Lesson 2 • Beginner

    Variables & Data Types 📦

    By the end of this lesson you'll store text, numbers, and true/false values in $variables, tell PHP's types apart with var_dump, and sidestep the == pitfalls that trip up almost every beginner.

    What You'll Learn in This Lesson

    • Create variables with the $ prefix and store values in them
    • Recognise PHP's main types: string, int, float, bool, and null
    • Inspect any value's type with var_dump and gettype
    • Interpolate variables in "double quotes" and join text with the . operator
    • Compare safely with === and avoid == type-juggling surprises
    • Define unchanging values with const and define

    1️⃣ Creating Variables

    A variable is a named place to keep a value so you can use it later. In PHP a variable name always begins with a $, followed by a letter or underscore, then letters, numbers, or underscores — for example $name or $first_name. You create one by assigning a value with a single =, which means "store this in the box" — not "is equal to". Names are case-sensitive, so $Name and $name are two different boxes.

    Declaring and reusing variables
    <?php
    // A variable is a named box that holds a value.
    // In PHP every variable name starts with a dollar sign ( $ ).
    
    $name = "Alice";        // a string  — text in quotes
    $age  = 28;             // an int    — a whole number
    $price = 49.99;         // a float   — a number with a decimal point
    $isMember = true;       // a bool    — only ever true or false
    $nickname = null;       // null      — "no value yet"
    
    // Inside DOUBLE quotes, PHP swaps a $variable for its value (interpolation).
    echo "Name:  $name\n";
    echo "Age:   $age\n";
    echo "Price: $price\n";
    
    // The = sign means "store this", NOT "is equal to".
    $age = 29;              // overwrite the box: $age is now 29
    echo "Next year: $age\n";
    ?>
    Output
    Name:  Alice
    Age:   28
    Price: 49.99
    Next year: 29
    This is real code — run it for free atonecompiler.com/phpor in your own editor.

    Notice the last two lines: assigning to $age again simply replaces what was inside. A variable holds one value at a time — the most recent thing you put in it.

    2️⃣ PHP's Data Types

    The type of a value is what kind of thing it is. PHP has eight types in total — string (text), int (whole numbers), float (decimals), bool (true/false), null (no value), plus array, object, and callable for later lessons. You'll use the first five constantly. The single most useful tool for learning them is var_dump(), which prints both the type and the value.

    The five everyday types, dumped
    <?php
    // PHP has 8 types. You'll use these 5 every day.
    $title   = "PHP Basics";   // string  — text
    $views   = 1500;           // int     — whole number
    $rating  = 4.5;            // float   — decimal number
    $isLive  = false;          // bool    — true / false
    $author  = null;           // null    — deliberately empty
    
    // var_dump() shows the TYPE and the value — your best debugging friend.
    var_dump($title);
    var_dump($views);
    var_dump($rating);
    var_dump($isLive);
    var_dump($author);
    
    // gettype() returns just the type name as a string.
    echo gettype($views) . "\n";   // integer
    echo gettype($rating) . "\n";  // double  (PHP calls floats "double")
    ?>
    Output
    string(9) "PHP Basics"
    int(1500)
    float(4.5)
    bool(false)
    NULL
    integer
    double
    This is real code — run it for free atonecompiler.com/phpor in your own editor.

    Two things to file away: var_dump shows a string's length (string(9) means 9 characters), and PHP confusingly calls a float a "double" when you ask gettype(). That's a historical quirk — double and float mean the same thing in PHP.

    3️⃣ Dynamic, Loose Typing

    Unlike Java or C#, PHP is dynamically typed: you never write the type when you create a variable, and PHP works it out from the value. The same variable can even change type later — put text in it now, a number in it next. This is called loose typing, and it's flexible and fast to write, but it's also the reason for the comparison surprises you'll meet in section 5.

    One variable, three types
    <?php
    // PHP is DYNAMICALLY typed: you never declare a type,
    // and the same box can hold different types over time.
    $data = "42";              // right now it's a string
    echo gettype($data) . "\n";   // string
    
    $data = 42;                // now the very same variable holds an int
    echo gettype($data) . "\n";   // integer
    
    $data = [1, 2, 3];         // now it's an array
    echo gettype($data) . "\n";   // array
    
    // This flexibility is handy — but it's why the == pitfalls below exist.
    ?>
    Output
    string
    integer
    array
    This is real code — run it for free atonecompiler.com/phpor in your own editor.

    4️⃣ Quotes, Interpolation & Concatenation

    How you quote a string changes what PHP does with it. Double quotes ("...") interpolate — PHP swaps any $variable inside for its value and processes escapes like \n. Single quotes ('...') are literal — you get the characters exactly as typed, $name and all. To stick strings together, use the dot operator (.), which is PHP's concatenation operator (not +).

    Double vs single quotes, and the . operator
    <?php
    $name = "Sam";
    
    // DOUBLE quotes interpolate: $name is replaced by its value.
    echo "Hello, $name!\n";          // Hello, Sam!
    
    // SINGLE quotes are literal: you get the text $name verbatim.
    echo 'Hello, $name!' . "\n";     // Hello, $name!
    
    // The dot ( . ) joins (concatenates) strings together.
    $greeting = "Hi, " . $name . "!";
    echo $greeting . "\n";           // Hi, Sam!
    
    // Curly braces remove all doubt about where a variable name ends.
    $item = "cup";
    echo "I have two {$item}s.\n";   // I have two cups.
    ?>
    Output
    Hello, Sam!
    Hello, $name!
    Hi, Sam!
    I have two cups.
    This is real code — run it for free atonecompiler.com/phpor in your own editor.

    Now you try. Fill in each ___ using the 👉 hint, then run it and check against the Output panel.

    🎯 Your turn: pick the right type
    <?php
    // 🎯 YOUR TURN — fill in each blank marked ___ , then run it.
    // Each box should hold the right type for the value described.
    
    $city  = ___;     // 👉 a string: your city in "double quotes"
    $year  = ___;     // 👉 an int: a whole number like 2026
    $score = ___;     // 👉 a float: a decimal like 9.5
    
    echo gettype($city) . "\n";    // should print: string
    echo gettype($year) . "\n";    // should print: integer
    echo gettype($score) . "\n";   // should print: double
    
    // ✅ Expected output:
    //    string
    //    integer
    //    double
    ?>
    Output
    string
    integer
    double
    Fill the three ___ blanks with a string, an int, and a float. The three lines of output should read string, integer, double.

    One more — this time about quoting and joining strings.

    🎯 Your turn: interpolate and concatenate
    <?php
    // 🎯 YOUR TURN — pick the RIGHT quotes so $name is interpolated.
    $name = "Sam";
    
    // 1) Make this print:  Hi, Sam!   (the value, not the text $name)
    echo ___Hi, $name!___ . "\n";   // 👉 wrap the text in DOUBLE quotes
    
    // 2) Join two strings with the dot operator into one greeting.
    echo "Welcome " ___ $name . "!\n";   // 👉 replace ___ with a dot  .
    
    // ✅ Expected output:
    //    Hi, Sam!
    //    Welcome Sam!
    ?>
    Output
    Hi, Sam!
    Welcome Sam!
    Use double quotes so $name interpolates, and replace the second ___ with a dot . to join the strings.

    5️⃣ Type Juggling: == vs ===

    Type juggling is PHP automatically converting types during an operation — "5" + 3 gives 8 because the string is turned into a number. It also happens during loose comparison with ==, which converts both sides to a common type first. That's why 5 == "5" is true. The fix is strict comparison with ===, which checks value and type, so 5 === "5" is false. Use === by default and only use == when you genuinely want juggling.

    Loose vs strict comparison
    <?php
    // == compares VALUES after juggling types (loose).
    // === compares value AND type (strict). Prefer === almost always.
    
    var_dump(5 == "5");      // true  — "5" is juggled to the int 5
    var_dump(5 === "5");     // false — int vs string, so strict fails
    
    var_dump(0 == "");       // false — modern PHP (8+); was a classic trap before
    var_dump("abc" == 0);    // false — non-numeric string is NOT juggled to 0 here
    
    var_dump(1 === 1);       // true  — same value, same type
    var_dump(null == false); // true  — both are "empty/falsy"
    var_dump(null === false);// false — different types
    ?>
    Output
    bool(true)
    bool(false)
    bool(false)
    bool(false)
    bool(true)
    bool(true)
    bool(false)
    This is real code — run it for free atonecompiler.com/phpor in your own editor.

    PHP 8 cleaned up the worst of the old traps (for example 0 == "hello" used to be true and is now false), but loose comparison can still surprise you with empty values and null. Reaching for === removes the guesswork entirely.

    6️⃣ Constants

    A constant is a value that's fixed once and can never change — perfect for things like a tax rate or a maximum limit. Constants have no $ and are written UPPER_CASE by convention. Define one with const (the modern, preferred way) or the older define() function. Trying to reassign a constant is a fatal error — which is exactly the safety you want for values that must never drift.

    const and define()
    <?php
    // A constant never changes once set. By convention it's UPPER_CASE
    // and has NO dollar sign.
    
    const MAX_USERS = 100;        // PHP-preferred, set at compile time
    define('TAX_RATE', 0.20);     // older style, works at run time too
    
    $subtotal = 50.00;
    $total = $subtotal + ($subtotal * TAX_RATE);
    
    echo "Tax rate: " . (TAX_RATE * 100) . "%\n";   // 20%
    echo "Total:    $" . $total . "\n";             // 60
    echo "Seat cap: " . MAX_USERS . "\n";           // 100
    
    // MAX_USERS = 200;  // would be a fatal error — constants can't be reassigned.
    ?>
    Output
    Tax rate: 20%
    Total:    $60
    Seat cap: 100
    This is real code — run it for free atonecompiler.com/phpor in your own editor.

    7️⃣ Heredoc & Nowdoc

    For multi-line text — an email body, a block of HTML — quotes get awkward. Heredoc (<<<LABEL) is like double quotes spread over many lines: it interpolates your variables. Nowdoc (<<<'LABEL', with the label in single quotes) is like single quotes: everything is literal. In both, the closing label must sit at the start of its own line.

    Heredoc interpolates, nowdoc is literal
    <?php
    $name = "Ada";
    $lang = "PHP";
    
    // HEREDOC ( <<<"LABEL" ) acts like double quotes: it interpolates $variables.
    $bio = <<<TEXT
    Name: $name
    Learns: $lang
    TEXT;
    
    // NOWDOC ( <<<'LABEL' ) acts like single quotes: everything is literal.
    $raw = <<<'TEXT'
    This $name is printed exactly as written.
    TEXT;
    
    echo $bio . "\n";
    echo $raw . "\n";
    ?>
    Output
    Name: Ada
    Learns: PHP
    This $name is printed exactly as written.
    This is real code — run it for free atonecompiler.com/phpor in your own editor.

    Common Errors (and the fix)

    • "Warning: Undefined variable $name" — you read a variable before giving it a value, or you mistyped its name (remember names are case-sensitive: $Name$name). Assign the variable first, and check your spelling.
    • Your text shows $name literally instead of the value — you used single quotes. Single quotes don't interpolate. Switch to double quotes: "Hi, $name".
    • A comparison is unexpectedly true — you used == and PHP juggled the types (e.g. 5 == "5"). Use === so value and type must match.
    • "Uncaught Error: Undefined constant" or odd output around a name — you wrote a variable without its $. Every PHP variable needs the dollar sign: it's $name, never bare name.

    Pro Tips

    • 💡 Reach for === by default. Strict comparison saves you from almost every type-juggling bug; use == only when you mean to juggle.
    • 💡 var_dump() is your debugger. When a value behaves oddly, dump it — seeing string("5") vs int(5) usually explains the bug instantly.
    • 💡 Name boxes for what they hold. $userEmail beats $x — your future self will thank you.

    📋 Quick Reference — Variables & Types

    SyntaxExampleWhat It Does
    $var = value;$age = 25;Create / assign a variable
    var_dump()var_dump($age)Show type and value
    gettype()gettype($age)Return the type name
    "...$v...""Hi $name"Double quotes interpolate
    '...''Hi $name'Single quotes are literal
    ."a" . "b"Join (concatenate) strings
    ===$a === $bStrict equality (value + type)
    constconst MAX = 10;Define a constant (modern)
    define()define('PI', 3.14);Define a constant (run time)

    Frequently Asked Questions

    Q: Why does every PHP variable start with a dollar sign?

    The $ is how PHP's parser tells a variable apart from everything else — function names, constants, and keywords have no $. It means PHP can read $name anywhere (even inside a double-quoted string) and instantly know it's a variable to look up. Forget the $ and PHP treats the bare word as a constant instead, which is one of the most common beginner errors.

    Q: What's the difference between == and === in PHP?

    == is loose equality: it converts the two values to a common type before comparing, so 5 == "5" is true. === is strict equality: the values must be the same type AND the same value, so 5 === "5" is false. Because loose comparison produces surprising results, the modern best practice is to use === almost everywhere and only reach for == when you deliberately want type juggling.

    Q: When should I use double quotes vs single quotes for strings?

    Use double quotes when you want PHP to interpolate variables and escape sequences — "Hi, $name\n" becomes Hi, Alice followed by a newline. Use single quotes when you want the text exactly as written — '$name\n' stays as the literal characters $name\n. Single quotes are also a hair faster because PHP doesn't scan them for variables, but the real choice is about whether you want interpolation.

    Q: What is type juggling and why is it a problem?

    Type juggling is PHP automatically converting a value's type during an operation — for example "5" + 3 gives 8 because the string is juggled to a number. It's convenient but can hide bugs: a loose == comparison can return true for values you'd expect to differ. Use var_dump() to see an actual type, use === to compare safely, and cast explicitly with (int) or (float) when you want a conversion you control.

    Q: What's the difference between const and define() for constants?

    Both create a constant — an UPPER_CASE name with no $ that cannot be reassigned. const is defined at compile time, must sit in the top scope of a file or class, and is the preferred modern style. define() runs at run time, so you can call it conditionally (for example inside an if block) or build the name dynamically. For ordinary fixed values, reach for const.

    Mini-Challenge: Product Receipt

    No code is filled in this time — just a brief and an outline. Write it yourself, run it on onecompiler.com/php or your own machine, then check your result against the expected output in the comments. This is exactly the write-run-check loop you'll use on every real script.

    🎯 Mini-Challenge: build a tiny receipt
    <?php
    // 🎯 MINI-CHALLENGE: A tiny product receipt.
    // No code is filled in — work from the steps below, then run it.
    //
    // 1. Make a constant TAX_RATE set to 0.10  (use const, UPPER_CASE, no $).
    // 2. Make $product (a string) and $price (a float, e.g. 20.00).
    // 3. Work out $tax = $price * TAX_RATE  and  $total = $price + $tax.
    // 4. echo three lines using DOUBLE quotes so the $variables interpolate:
    //       Product: <name>
    //       Price:   $<price>
    //       Total:   $<total>   (price + 10% tax)
    //
    // ✅ Expected output (product "Mug", price 20.00):
    //    Product: Mug
    //    Price:   $20
    //    Total:   $22
    
    // your code here
    ?>
    Use a const for the tax rate, work out the tax and total, then echo three labelled lines with double quotes so the variables interpolate.

    🎉 Lesson Complete!

    • ✅ Every variable starts with $, and = means "store this"
    • ✅ The five everyday types are string, int, float, bool, and null
    • var_dump() and gettype() reveal a value's type
    • ✅ PHP is dynamically typed — a variable's type can change as you reassign it
    • ✅ Double quotes interpolate, single quotes are literal, and . joins strings
    • ✅ Prefer === over == to avoid type-juggling surprises
    • const and define() create values that never change
    • Next lesson: Operators & Expressions — do maths, compare, and combine your values

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service