PHP Tutorial · PHP Basics · Lesson 5 of 38

PHP Variables

Create variables with $, name them, and understand scope.

Creating variables

PHP variables start with a $ sign. There's no declaration keyword — a variable is created when you assign to it:

Example 1Try it yourself
<?php
$name = "Ada";
$age = 36;
$height = 1.68;
$isAdmin = true;
echo "$name is $age years old.\n";
echo 'Single quotes don\'t expand $name' . "\n";

Output

Ada is 36 years old.
Single quotes don't expand $name

Rules: a name starts with a letter or underscore, contains letters, digits and underscores, and is case-sensitive. Use $camelCase or $snake_case consistently.

Variable scope

Variables defined outside a function are not visible inside it. Pass them as parameters (best), or use global (avoid):

Example 2Try it yourself
<?php
$siteName = "ReadyCamel";

function title(string $page, string $site): string
{
    return "$page | $site";
}

function broken(): string
{
    return isset($siteName) ? "visible" : "not visible inside the function";
}

echo title("Home", $siteName), "\n";
echo broken(), "\n";

Output

Home | ReadyCamel
not visible inside the function

static variables

A static variable inside a function keeps its value between calls:

Example 3Try it yourself
<?php
function nextId(): int
{
    static $id = 0;
    return ++$id;
}
echo nextId(), " ", nextId(), " ", nextId(), "\n";

Output

1 2 3

Test yourself

Which character must every PHP variable name start with?

  1. @
  2. $
  3. &
  4. %
Show answer

Answer: $