Skip to main content
PHP for Beginners
CHAPTER 04 Beginner

PHP Variables and Data Types

Updated: May 12, 2026
15 min read

# Chapter 4: PHP Variables and Data Types

1. Introduction

Welcome to Chapter 4! In any programming language, variables act as "containers" for storing data. Imagine a variable as a labeled box where you can put a piece of information, take it out later, or change it whenever you want. PHP is a "loosely typed" language, meaning you don't have to declare what kind of data is going into the box ahead of time. In this chapter, we will master variables, variable naming rules, and the fundamental data types in PHP.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Declare and assign values to variables using the $ symbol.
  • Understand PHP's variable naming conventions and rules.
  • Identify and use Strings, Integers, Floats, and Booleans.
  • Grasp the basics of Arrays and NULL data types.
  • Debug variables using the vardump() function.

3. Variables

In PHP, every variable must start with a dollar sign $, followed by the name of the variable.

Rules for naming variables:

  • Must start with a letter or an underscore .
  • Cannot start with a number (e.g., $1name is invalid).
  • Can only contain alphanumeric characters and underscores (A-z, 0-9, and _).
  • Variables are case-sensitive ($name and $NAME are two different variables).

php
1234567
<?php
$greeting = "Hello";
$age = 25;
$_status = "Active";

echo $greeting; // Outputs: Hello
?>

4. PHP Data Types

Variables can store different types of data. PHP supports several data types:

Strings

A string is a sequence of characters, like text. It must be wrapped in single ' or double " quotes. $name = "Alice";

Integers

An integer is a non-decimal number between -2,147,483,648 and 2,147,483,647. $score = 100;

Floats (Doubles)

A float is a number with a decimal point or a number in exponential form. $price = 19.99;

Booleans

A boolean represents two possible states: true or false. These are crucial for conditional logic (which we will learn later). $isadmin = true; $isloggedin = false;

Arrays

An array stores multiple values in a single variable. We will dedicate a whole chapter to arrays later, but here is a preview. $colors = array("Red", "Green", "Blue");

NULL

Null is a special data type that has only one value: NULL. A variable of data type NULL is a variable that has no value assigned to it. $empty
variable = NULL;

5. Checking Data Types with vardump()

When debugging, you often need to know exactly what type of data a variable holds. The vardump() function tells you both the data type and the value.
php
12345678
<?php
$myString = "Hello!";
$myInt = 42;

var_dump($myString); // Outputs: string(6) "Hello!"
echo "<br>";
var_dump($myInt);    // Outputs: int(42)
?>

6. Real-World Examples

Let's look at how a user profile might be represented using various data types.
php
12345678
<?php
// User Profile Data
$username = "john_doe";         // String
$age = 28;                      // Integer
$account_balance = 250.75;      // Float
$is_premium_member = true;      // Boolean
$subscription_type = NULL;      // NULL (Not set yet)
?>

7. Output Explanations

When using echo to output booleans, PHP converts true to the integer 1, and false to an empty string "" (which shows nothing on the screen). Therefore, echo $ispremiummember; would output 1. To properly inspect booleans or arrays, always use var_dump().

8. Variable Parsing in Strings

A powerful feature of PHP is that variables can be evaluated *inside* double-quoted strings. This is called variable parsing or interpolation.
php
123456789
<?php
$city = "New York";

// Double quotes: Parses the variable
echo "I live in $city."; // Outputs: I live in New York.

// Single quotes: Treats the variable name as plain text
echo &#039;I live in $city.'; // Outputs: I live in $city.
?>

9. Common Mistakes

  • Forgetting the $ sign: Trying to write name = "John"; instead of $name = "John";.
  • Mixing up Quotes: Forgetting that single quotes do not parse variables.
  • Spaces in Variable Names: Using $first name = "John"; will cause a fatal error. Use CamelCase ($firstName) or snakecase ($firstname).

10. Best Practices

  • Choose descriptive variable names. $userage is much better than $a.
  • Stick to a consistent naming convention throughout your project (e.g., snakecase).
  • Initialize your variables. If a variable might not have data immediately, set it to NULL or an empty string "" rather than leaving it undeclared to avoid warnings.

11. Exercises

  1. 1. Declare a string variable holding your favorite movie and echo it.
  1. 2. Declare an integer variable for your birth year, a float for your height, and use var_dump() to inspect both.
  1. 3. Write a sentence using double quotes that dynamically includes three different variables.

12. Mini Project: Student Information System

Task: Create a dynamic student ID card using PHP variables and HTML layout.
php
12345678910111213141516171819202122232425262728293031
<?php
// Student Data
$student_name = "Emma Watson";
$student_id = 987654;
$gpa = 3.8;
$is_enrolled = true;
$major = "Computer Science";
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Student ID Card</title>
    <style>
        .card { border: 2px solid black; padding: 20px; width: 300px; border-radius: 10px; font-family: sans-serif; }
        .highlight { color: blue; font-weight: bold; }
    </style>
</head>
<body>
    <div class="card">
        <h2>Student ID Card</h2>
        <hr>
        <p><strong>Name:</strong> <span class="highlight"><?php echo $student_name; ?></span></p>
        <p><strong>ID Number:</strong> <?php echo $student_id; ?></p>
        <p><strong>Major:</strong> <?php echo $major; ?></p>
        <p><strong>GPA:</strong> <?php echo $gpa; ?></p>
        <p><strong>Enrolled Status:</strong> <?php var_dump($is_enrolled); ?></p>
    </div>
</body>
</html>

13. Coding Challenges

Challenge 1: Create two integer variables. Create a third variable that stores the sum of the first two (using the + sign) and echo the result inside a descriptive string.
php
1234567
<?php
// Solution Snippet
$apples = 5;
$oranges = 3;
$total_fruit = $apples + $oranges;
echo "I have a total of $total_fruit fruits.";
?>

14. MCQs with Answers

1. Which of the following is a valid PHP variable name? A) $1stname B) $first-name C) $firstname D) firstname *Answer: C*

2. Which data type is used to represent true or false? A) String B) Float C) NULL D) Boolean *Answer: D*

3. What does vardump() do? A) Deletes the variable from memory. B) Outputs the data type and value of a variable. C) Converts a variable to a string. D) Dumps the variable into a database. *Answer: B*

15. Interview Questions

Q: What does it mean when we say PHP is a "loosely typed" language? *A:* It means you do not need to declare the data type (like int, string, float) when creating a variable. PHP automatically determines the data type based on the value assigned to the variable.

Q: What is the difference between single and double quotes in PHP strings? *A:* Double quotes parse (evaluate) variables inside them, allowing for string interpolation. Single quotes treat everything as literal text, meaning variable names will not be evaluated. Single quotes are slightly faster to process for static text.

16. FAQs

Q: Can a variable change its data type later? *A:* Yes. Because PHP is loosely typed, you can assign an integer to a variable, and later assign a string to that exact same variable without errors.

17. Summary

You have mastered PHP variables and data types! You learned the strict rules for naming variables using the $ symbol, explored strings, integers, floats, booleans, and NULLs, and discovered how to embed variables directly into double-quoted strings. You also learned the invaluable var_dump() debugging tool.

18. Next Chapter Recommendation

Variables are great, but they are more powerful when you can manipulate them. In Chapter 5: PHP Operators, we will learn how to perform mathematics, join strings together, and compare different variables!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·