Variables, quotes and types
A variable is a named place for a value that may change. Its name starts with a dollar sign, then letters, digits or underscores: $name, $books_read. The sign = does not mean “equals”; it assigns: it puts the value on the right into the variable on the left. You need not declare a variable first; PHP decides its type from the value. Variable names are case-sensitive, so $total and $Total are two different variables. Quotes matter. In double quotes PHP replaces a variable by its value; in single quotes it prints the text exactly as written. To join pieces use a dot. The main types are string (text), integer (a whole number), double (a number with a decimal part) and boolean (true or false). The function gettype tells you the type. If a variable has no value yet, give it one yourself, for example $x = null; reading a variable that was never set gives a warning.
| Type | Example | gettype prints |
|---|---|---|
| text | "Mona" | string |
| whole number | 123 | integer |
| decimal number | 1.23 | double |
| true or false | true | boolean |
| no value | null | NULL |
| Code | What the page shows |
|---|---|
| echo "my name is $name"; | my name is Mona |
| echo 'my name is $name'; | my name is $name |
| echo 'my name is ' . $name; | my name is Mona |
1<?php 2$books = 3; 3$books = 5; 4$total = 5; 5$Total = 9; 6echo "Books: " . $books . " " . $total . " " . $Total; 7?>
Books: 5 5 9
1<?php 2echo gettype("Mona"), " ", gettype(123), " ", gettype(1.23), " ", gettype(true), " ", gettype(null); 3?>
string integer double boolean NULL
On paper write a PHP block with three variables for a club member (a name, a number of books and whether the card is active). Print one sentence that uses all three, once with double quotes and once with the dot. Then write which gettype word each variable gives.