Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 1

Declaring and Using Variables

Recommended resources

Hello! Welcome to the first lesson of your PHP Mastery course.

As we discussed, you're already familiar with the basics of PHP. Our goal in this first module is to build a rock-solid foundation by refreshing those fundamentals. This will ensure we're all on the same page before diving into more complex topics like object-oriented programming, security, and building APIs.

Today's lesson focuses on the absolute cornerstone of any programming language: variables and data types. We'll review how to declare variables in PHP and take a closer look at the most common data types you'll be working with. By the end of this session, you'll be able to confidently declare and use variables with different data types.

1. What is a Variable?

In programming, a variable is a container for storing information. Think of it as a labeled box where you can put data, retrieve it later, or change it.

In PHP, there are a few simple but strict rules for defining variables.

PHP Variable Syntax and Rules
This image breaks down the syntax for declaring a variable in PHP and lists the essential naming conventions.

As a quick refresher, here are the key rules from the image:

  • All variables in PHP start with a dollar sign ($).
  • A variable name must start with a letter or an underscore (_). It cannot start with a number.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
  • Variable names are case-sensitive! This is a common source of bugs, so remember that $name and $Name are two different variables.

2. PHP: A Dynamically Typed Language

One of PHP's core characteristics is that it's a dynamically typed language. This means you don't have to explicitly tell PHP what type of data a variable will hold. PHP automatically figures it out at runtime based on the value you assign.

To understand what this means in practice, please watch the first two minutes of the following video. It provides a great explanation of dynamic typing and contrasts it with statically typed languages you might have heard of, like C++ or Java.

PHP Data Types - Typecasting Overview & How It Works - Full PHP 8 Tutorial

This video from the Program With Gio channel explains the concept of dynamic typing in PHP and introduces the main data categories.

Watch from the beginning until timestamp 02:09. Focus on the distinction between dynamically typed and statically typed languages.

This flexibility is one of the reasons PHP is so popular for web development, but as the video mentions, it also means we need to be careful about what kind of data our variables hold.


3. The Basic (Scalar) Data Types

Now, let's review the fundamental data types, often called scalar types. These are the simplest building blocks for your data. We'll cover four of them: string, integer, float, and boolean.

The following video from the "Bro Code" channel gives a very practical, hands-on demonstration of each of these types.

PHP variables and data types

This video provides a practical walkthrough of declaring, using, and displaying variables for the four main scalar data types.

Watch from the beginning until timestamp 11:01. The video is clearly sectioned, covering strings, integers, floats, and booleans one by one. Pay attention to how each type is declared and how it behaves when displayed with echo.

Let's summarize the key points from the video for each type.

String

A string is a sequence of characters, like "Hello, world!". In PHP, you can use either single quotes (') or double quotes ("). A key difference, which we'll explore more later, is that double-quoted strings can include variables directly (a feature called interpolation).

$greeting = "Hello";
$target = 'World';

// You can join strings with the concatenation operator (.)
echo $greeting . ", " . $target . "!"; // Outputs: Hello, World!

Integer

An integer is a whole number without a decimal point. It can be positive, negative, or zero.

$age = 30;
$temperature = -5;
$itemCount = 100;

Float (or Double)

A floating-point number, or float, is a number with a decimal point. They are often used for prices, measurements, or any value that requires fractional precision.

$price = 19.99;
$pi = 3.14159;
$taxRate = 0.075;

Boolean

A boolean represents a truth value and can only be true or false. They are the foundation of all logic and control flow in your programs (e.g., in if statements).

$isLoggedIn = true;
$hasErrors = false;

As the video showed, when you echo a boolean, true is converted to "1" and false is converted to an empty string "". This is an example of PHP's automatic type conversion, which we'll look at next.


4. How to Check a Variable's Type

Since PHP is dynamically typed, it's often useful, especially during debugging, to check what type of data a variable currently holds. There are two indispensable tools for this.

The video you watched earlier, "PHP Data Types" by Program With Gio, has an excellent section on this.

PHP Data Types - Typecasting Overview & How It Works - Full PHP 8 Tutorial

This section of the video demonstrates the two most important functions for inspecting variables: gettype() and var_dump().

Please watch from 03:05 to 04:18.

  • gettype($variable): This function returns a string representing the data type of the variable (e.g., "integer", "string", "boolean").
  • var_dump($variable): This is one of the most useful functions for a PHP developer. It prints detailed information about a variable, including its type, its value, and, for strings, its length.

Here is a quick example:

$items = 5;
$label = "Total items: ";
$onSale = false;

var_dump($items);    // outputs: int(5)
var_dump($label);    // outputs: string(13) "Total items: "
var_dump($onSale);   // outputs: bool(false)
Test your understanding!

What would var_dump($myVar); output for the following code?

$myVar = "99.9";
Show answer

It would output: string(4) "99.9"

Even though the value looks like a number, because it's enclosed in quotes, PHP treats it as a string. var_dump reveals both the type (string) and the length (4 characters: '9', '.', '9', and the closing quote).


5. Other Data Types: A Quick Look

Besides the four scalar types, PHP has a few other types for more complex data structures. We will only introduce them briefly here, as they each have dedicated lessons later in the course.

This article provides a clean classification of PHP's data types into three groups: Scalar, Compound, and Special.

PHP Data Types - Scalar, Compound, and Special

To get a complete picture, please read the introductory sections of this article from Codeguage, which organizes PHP's data types into logical groups.

Read the sections titled 'Classifications of data types', 'Compound types' (just the brief intro), and 'Special types'. This should take about 5 minutes. The goal is just to be aware of the categories, not to master them yet.

To summarize the reading:

  • Compound Types: These are for grouping other values.
    • array: An ordered map that can hold multiple values. (We'll cover this in detail soon!)
    • object: An instance of a class, crucial for Object-Oriented Programming. (Module 2)
  • Special Types:
    • null: A special type that means "no value". A variable is null if it has been assigned the constant NULL or has not been set to any value yet.
    • resource: A special variable holding a reference to an external resource, like a database connection or an open file.

This image provides a great visual summary of all the types we've mentioned.

PHP Data Types Overview
A visual chart categorizing PHP's data types into Scalar, Compound, and Special types with code examples for each.

6. Conclusion

Great work on this first refresher lesson! We've established a strong baseline for the rest of the course.

Here are the key takeaways:

  • Variables in PHP are containers for data, always start with a $ sign, and are case-sensitive.
  • PHP is a dynamically typed language, meaning it infers a variable's type from its value at runtime.
  • The four fundamental scalar types are string, integer, float, and boolean.
  • The var_dump() function is your most powerful tool for inspecting a variable's type and value for debugging.
  • PHP also supports compound types like array and object, and special types like null.

In our next lesson, we'll put these variables to work. Now that you know how to store data, we'll learn how to manipulate it using arithmetic, comparison, and logical operators. This will unlock the ability to perform calculations and make decisions in your code.