Variables and arrays
Store values in $variables, learn the main data types, join strings, and keep lists of values in arrays.
Variables start with $
A variable is a named box that holds a value. In PHP every variable name starts with a dollar sign.
<?php
$name = 'Grace';
$age = 17;
$height = 1.62;
$isMember = true;
echo $name; // Grace
echo $age + 1; // 18
| Type | Example | Used for |
|---|---|---|
| string | 'Grace' | Text |
| int | 17 | Whole numbers |
| float | 1.62 | Numbers with decimals |
| bool | true / false | Yes or no |
| array | ['HTML', 'CSS'] | Lists of values |
| null | null | No value |
Joining strings
Use a dot . to join (concatenate) strings. Strings in double quotes also replace variables inside them; strings in single quotes do not.
<?php
$name = 'Grace';
$age = 17;
echo 'Hello, ' . $name . '!'; // Hello, Grace!
echo "$name is $age years old."; // Grace is 17 years old.
echo '$name is $age years old.'; // $name is $age years old.
Arrays: lists of values
<?php
$courses = ['HTML', 'CSS', 'PHP'];
echo $courses[0]; // HTML (counting starts at 0)
$courses[] = 'MySQL'; // add to the end
echo count($courses); // 4
Associative arrays: named keys
Instead of numbers, an associative array uses names (keys) for each value. It is perfect for describing one thing, such as a student.
<?php
$student = [
'name' => 'Tunde',
'parish' => 'Grace Chapel',
'age' => 19,
];
echo $student['name'] . ' attends ' . $student['parish'];
print_r($student); // shows the whole array, handy while learning
Tunde attends Grace Chapel Array ( [name] => Tunde [parish] => Grace Chapel [age] => 19 )
Exercise
Create an associative array $book with a title, an author and a year, then print one sentence that uses all three.
<?php
$book = [];
Show a possible solution
<?php
$book = ['title' => 'Things Fall Apart', 'author' => 'Chinua Achebe', 'year' => 1958];
echo $book['title'] . ' was written by ' . $book['author'] . ' in ' . $book['year'] . '.';
Check your understanding
Quick check
Which is a valid PHP variable?
Quick check
What joins two strings in PHP?
Quick check
$c = ['HTML', 'CSS']; What is $c[1]?