This is a very basic lesson about PHP variables. We will get back to variables a few more times in further lessons. A variable is a named entity that stores some value. PHP variables should start with $ sign. Consider this example:

$name = 'Anastasia';

echo 'Hello ' . $name;

That will output Hello Anastasia. And there is something new: a dot operator. This operator is used to concatenate (or join) strings. You also could write it like that:

$name = 'Anastasia';
$greeting = 'Hello ' . $name;

echo $greeting;

And that would give You the same result.

You can also store numbers in a variable and do arithmetic operations on them:

$name = 'Anastasia';
$this_year = 2019;
$age = 29;
$birth_year = $this_year - $age;

echo 'My name is ' . $name . ' and my birth year is ' . $birth_year;

Notice that we used a dot operator with numbers, however a dot operator is a string operator. In this case numbers are converted to strings. Also you can do the opposite:

$a = 5;
$b = '10';

echo $a + $b;

In that case the string stored in the variable $b is converted to a number — because we used an arithmetic operation.

There's another syntax for strings — double quotes. Using double quotes gives you additional features you should know about:

$name = 'Anastasia';
$age = 29;

echo "My name is $name and I'm $age years old";

So, when using a double quotes string syntax, you can write variables directly inside a string. There are more features you can use with double quotes string syntax, but we will discuss them later. Still you should prefer a single quotes string syntax unless you really need a double quotes one.

Lesson 2
Lesson 4
Share this page:

Learning plan

Choose the best way to start, and let's start!
Embedding PHP script into HTML
3. Variables
The very basics of PHP variables
4. Arrays
The very basics of PHP arrays
The things you should know about PHP type system
The basement of PHP control flow structures you should learn before continue