Variables and arrays

Lesson 2 of 15 14 min read Free lesson

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
<?php
$name = 'Grace';
$age = 17;
$height = 1.62;
$isMember = true;

echo $name;          // Grace
echo $age + 1;       // 18
TypeExampleUsed for
string'Grace'Text
int17Whole numbers
float1.62Numbers with decimals
booltrue / falseYes or no
array['HTML', 'CSS']Lists of values
nullnullNo 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
<?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
<?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
<?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
Output
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.

Starting code
<?php
$book = [];
Show a possible solution
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]?

Hi there! đź‘‹ Have a question about the courses or joining the class? Ask me.