Kodokon kodokon.com

Variables, types, and strings

Learn how to store values in variables, tell the basic types apart, and put text together through concatenation or interpolation.

7 min · 3 questions

Open this lesson in Kodokon

A variable is a named box in which you store a value to reuse it later. In PHP, a variable name always begins with the $ symbol, followed by a meaningful name (letters, digits, no spaces). The = sign is the assignment: it stores the value on the right into the variable on the left. You read $age = 28; as: “the variable $age receives the value 28”.

PHP
<?php

$firstName = "Awa";
$age = 28;
$height = 1.65;
$isStudent = true;

echo $firstName;
echo $age;
Four variables, four different values.

Every value has a type, meaning its nature. The four basic types: the string (string), text between quotes like "Awa"; the integer (int), a whole number like 28; the float (float), a decimal number like 1.65 (with a dot, never a comma); and the boolean (bool), which can only be true or false. PHP figures out the type on its own from the value you write.

To put text together, PHP uses concatenation: the dot operator . glues two strings end to end. Be careful, it really is the dot that joins text in PHP, not + (which is reserved for adding numbers).

PHP
<?php

$city = "Lyon";
$message = "Welcome to " . $city . "!";

echo $message;
The dot . glues the pieces of text together.

Even more readable: interpolation. Inside a string in double quotes, PHP automatically replaces a variable with its value. Write it inside curly braces, like {$name}, to clearly mark its boundaries. Careful: inside single quotes '...', nothing is replaced, the text stays exactly as written. PHP can also do arithmetic with the classic operators: + (addition), - (subtraction), * (multiplication), / (division), and % (the modulo, the remainder of an integer division).

PHP
<?php

$name = "Awa";
echo "Hello {$name}!<br>";

$price = 20;
$quantity = 3;
$total = $price * $quantity;
$rest = 7 % 2;

echo "Total: {$total} euros<br>";
echo "Remainder: {$rest}";
Interpolation and calculations together.

Knowledge check

Make sure you remember the key points of this lesson.

  1. How do you recognize a variable in PHP?
    • Its name starts with the $ symbol
    • Its name must be in uppercase
    • It is declared with the var keyword
  2. Which operator joins two strings together?
    • +
    • .
    • &
  3. Which form replaces {$name} with its value in the displayed text?
    • echo "Hello {$name}"; with double quotes
    • echo 'Hello {$name}'; with single quotes
    • Both forms work the same way