SITERAW

Variables in PHP

⚠️ Heads up — this is a core chapter! Variables are a fundamental part of any programming language, and PHP is no exception. They're not some convoluted geeky concept — quite the opposite! They're here to make our lives easier. Without them, you wouldn't get very far. 😜

Variables allow us to temporarily store information in memory. That means we can remember a visitor's username, do calculations, and loads of other cool stuff!

What is a variable?

Just hearing the word "variable" probably makes you think of something that changes — and you'd be right. That's exactly what a variable does: it varies (go figure). But let's get down to brass tacks.

A variable is a tiny piece of information that's temporarily stored in memory. It's not built to last forever. In PHP, a variable (that bit of info) exists only while the page is being generated. Once the PHP page is done loading, poof! — the variables disappear from memory because they're no longer needed. So it's not like a file saved on your hard drive; it's just a temporary blip in RAM.

You're the one who decides when to create variables, and you do it whenever you need to keep track of something.

A Name and a Value

A variable always has two parts:

  • Its name – This is how you refer to it later. For example: visitor_age.
  • Its value – This is the actual info it contains, and yes, it can change. For example: 15.

So in this case, we have a variable called visitor_age with a value of 15.

You can change a variable's value whenever you like, do stuff with it, perform calculations, etc. And when you need it, just call its name and it'll politely tell you what it holds.

Like this:

  • "Hey! You there, visitor_age, what do you have inside you?"
  • "15."
  • "Thanks!"

These little critters might seem a bit fuzzy right now, but you'll soon see just how essential they are for building anything in PHP.

For instance, you can store the visitor's username in a variable called visitor_name, maybe something like "Bob". Then whenever you need it, you can use it to show a personalized welcome message like: "Hi Bob! Welcome to SiteRaw!".

The Different Types of Variables

Variables can store all kinds of data. We call these data types. Here are the main ones you'll need to know:

  • Strings (string) – This is just a fancy word for text. In PHP, all text is called a string. It can be short, long, a word, a novel — you name it. Example: "I am a string." Strings are usually written between double quotes " or single quotes '. Both work, but there's a subtle difference we'll get to later.
  • Integers (int) – These are whole numbers like 1, 2, 3, etc., including negatives like -1, -2. Example: 43
  • Floats (float) – These are decimal numbers like 14.738. You can go wild with decimal places if you want. Example: 14.738
  • Booleans (bool) – These are true or false values, super useful when you want to check if something is yes or no. You write true or false (without quotes). Example: true
  • NULL – Sometimes, a variable just holds... nothing. Yup, absolutely nothing. That's what NULL means. It's not really a "type" so much as a way to say "this variable is empty."

And there you have it — a quick intro to the types of info PHP can juggle for you. These are all you'll need to start building your site!

Let's get hands-on now. How do you create a variable and see what it contains?

Assigning a value to a variable

First up, let's assign a value to a variable. Then we'll display what it holds. This is where things start to click.

Playing with Variables

Let's keep it simple — and fun 😄

Try this:

<?php
$user_name = "SiteRawFan";
?>

This code creates a variable:

  • Named user_name
  • With a value of SiteRawFan

⚠️ A quick note: you can't have spaces in variable names. Use an underscore _ instead. Also avoid accents, cedillas, and other quirky symbols — PHP's not a fan.

Let's break it down:

  • The dollar sign $ always comes before a variable name. Think of it as a VIP badge: "Hey PHP, this is a variable!"
  • The equal sign = sets the variable's value. Like, "$visitor_age equals..."
  • Then comes the value itself — like 17.
  • Finally, the semicolon ; ends the instruction. It's like a full stop for code.

And what does that code actually display?

Absolutely nothing! 😄 Yep, unless you use echo, nothing gets shown. The server just creates the variable and... that's it. Using Different Data Types

Variables don't have to hold text — you can store numbers or booleans too!

<?php
$user_name = "Bob The SiteRaw Fan"; // text
$user_age = 15; // number
$user_is_noob = true; // boolean
$user_is_good_at_php = false; // another boolean

$user_age = 16; // birthday upgrade 🎂 ?>

Here's a recap of data types and how to use them:

Strings (string)

Store text by wrapping it in quotes — single ' or double ":

<?php
$user_name = "Bob the SiteRaw Fan";
$user_name = 'Bob the SiteRaw Fan';
?>

Need quotes inside your string? Escape them with a backslash \:

<?php
$var = "This \"website\" is SiteRaw";
$var = 'You\'re on SiteRaw!';
$var = 'This "website" is SiteRaw';
$var = "You're on SiteRaw!";
?>

Numbers (int and float)

Just write the number — no quotes needed!

<?php
$visitor_age = 15;
$weight = 67.5;
?>

Booleans (bool)

True or false — no quotes here either!

<?php
$am_i_a_noob = true;
$am_i_good_at_php = false;
?>

Null

If you want a variable to hold nothing at all, use NULL:

<?php
$no_value_yet = NULL;
?>

To sum up: strings go in quotes. Numbers, booleans, and NULL? No quotes. If you got that, you're ready to roll! 😎

Displaying and concatenating variables

You've learned how to create variables and store stuff in them. But so far, none of our code actually displays anything.

Displaying a Variable

Remember how we use echo to print text? You can do the same with variables:

<?php
$visitor_age = 15;
echo $visitor_age;
?>

That'll output:

15

🤔 Wait — shouldn't there be quotes after echo?

Nope! Not with variables. No quotes needed when echoing a variable.

Create a test PHP file with that code, and try it in your browser. You'll just see a plain white page with the number 15.

Concatenation (No, It's Not a Curse Word 😅)

Concatenation just means gluing things together — like text + variable + more text.

Let's say you want to write "The visitor is 15 years old."

Here's a basic version:

<?php
$visitor_age = 15;
echo "The visitor is ";
echo $visitor_age;
echo " years old";
?>

It works! But we can do better.

Method 1: Using Double Quotes

With double quotes, you can insert variables directly into the text:

<?php
$visitor_age = 15;
echo "The visitor is $visitor_age years old";
?>

Output:

The visitor is 15 years old

Nice and easy! But there's a catch...

Method 2: Using Single Quotes + the Dot Operator

This time, variables don't work inside the quotes:

<?php
$visitor_age = 15;
echo 'The visitor is $visitor_age years old'; // Nope!

That shows:

The visitor is $visitor_age years old

😱 Oh no! PHP didn't replace the variable!

Here's the fix — concatenate using dots:

<?php
$visitor_age = 15;
echo 'The visitor is ' . $visitor_age . ' years old';
?>

Much better! And bonus: this method is cleaner, clearer, and a bit faster too. Most pro PHP devs use single quotes with concatenation. It also makes your variables stand out better in your editor.

Doing Basic Math on Variables

Time to make your computer flex its muscles! PHP can do math too — and no, we're not diving into advanced calculus right away. Just the classics: addition, subtraction, multiplication, and division. You got this, right? 😜

We'll only use variables that hold numbers.

The Basics

Here are the main math symbols you'll use (they're on your number pad):

SymbolMeaning
+Addition
-Subtraction
*Multiplication
/Division

Examples:

<?php
$num = 3 + 4;       // 7
$num = 5 - 1;       // 4
$num = 3 * 5;       // 15
$num = 15 / 3;      // 5
$num = 3 * 5 + 2;   // 17
$num = (1 + 2) * 2; // 6
?>

Mental math time! Come on, don't be shy — it's good for you 😄

You can also use variables in calculations:

<?php
$num = 10;
$result = ($num + 5) * $num; // 150
?>

It's just logic — nothing scary here. If that made sense, you're solid. 😎

The Modulo Operator

Here's a slightly less common one: the modulo. It gives you the remainder after a division.

Example:

7 ÷ 3 = 2, remainder 1.

That remainder is what modulo gives you.

Use the % symbol:

<?php
$num = 10 % 5; // 0 – perfect division
$num = 10 % 3; // 1 – remainder 1
?>

What about square roots, exponents, and so on?

Those require functions, which we'll cover later. For now, these basics are more than enough for everyday PHP.

🎉 And that's a wrap for this chapter on PHP variables! With all this under your belt, you're more than ready for what's next. The upcoming chapters will be a breeze in comparison — and we've got some fun, hands-on examples coming your way! 😄

How to Build a Website in HTML and CSS

Enjoyed this PHP & MySQL course?

If you liked this lesson, you can find the book "How to Build a Website in HTML and CSS" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete PHP & MySQL workshop with many exclusive bonus chapters.

More information