A variable is a named container that holds a value, such as a student's name, a price or a list of marks. In PHP, every variable name starts with a dollar sign $.
Creating variables
You create a variable simply by assigning a value to it with =. There is no separate "declare" step and no need to say what type of value it holds.
<?php
$name = "Wanjiru";
$age = 19;
$fees = 45500.50;
$isEnrolled = true;
echo "$name is $age years old.\n";
echo "Fees: KSh $fees\n";
echo "Enrolled: $isEnrolled\n";Wanjiru is 19 years old. Fees: KSh 45500.5 Enrolled: 1
Two things to notice: PHP drops the unnecessary trailing zero in 45500.50, and true prints as 1 when turned into text. You will see why in Data Types.
Naming rules
- A variable starts with
$followed by a letter or underscore. - After that it may contain letters, numbers and underscores (
A-z,0-9,_). - It cannot start with a number:
$2ndPlaceis invalid,$secondPlaceis fine. - Names are case-sensitive:
$scoreand$Scoreare different variables.
Popular styles are $camelCase ($totalFees) and $snake_case ($total_fees). Pick one and use it consistently.
Changing a variable
A variable can be given a new value at any time, even a value of a different type. PHP is loosely typed: the type follows the value.
<?php
$counter = 5;
echo $counter . "\n";
$counter = $counter + 10;
echo $counter . "\n";
$counter = "five";
echo $counter . "\n";5 15 five
Printing variables inside strings
Inside double quotes, PHP replaces a variable with its value (this is called interpolation). When the variable name touches other letters, wrap it in curly braces so PHP knows where the name ends.
<?php
$item = "mango";
$count = 12;
echo "I bought $count {$item}s at the market.\n";
echo 'Single quotes: $count {$item}s' . "\n";I bought 12 mangos at the market.
Single quotes: $count {$item}sWithout the braces, "$items" would look for a variable called $items, which does not exist.
Variable scope
The scope of a variable is the part of the script where it can be used. PHP has three main scopes:
- Global scope: variables created outside any function.
- Local scope: variables created inside a function. They exist only while that function runs.
- Static variables: local variables that keep their value between function calls.
This surprises people coming from JavaScript: a function cannot see global variables automatically.
<?php
$school = "Maseno School"; // global
function showSchool()
{
$classroom = "Form 2B"; // local
echo "Classroom: $classroom\n";
echo "School inside function: " . ($school ?? "not visible") . "\n";
}
showSchool();
echo "School outside function: $school\n";Classroom: Form 2B School inside function: not visible School outside function: Maseno School
Inside the function, $school is a brand-new, empty local variable. Likewise, $classroom is gone once the function finishes.
The global keyword
To use a global variable inside a function, list it after the global keyword. PHP also keeps every global in the special array $GLOBALS.
<?php
$visits = 10;
function addVisit()
{
global $visits;
$visits++;
}
function addTwoVisits()
{
$GLOBALS['visits'] += 2;
}
addVisit();
addTwoVisits();
echo "Total visits: $visits";Total visits: 13
return. You will practise this in Functions.The static keyword
Normally a local variable is wiped clean each time the function ends. Mark it static and PHP remembers the value for the next call.
<?php
function nextTicket()
{
static $number = 0;
$number++;
return "Ticket #$number";
}
echo nextTicket() . "\n";
echo nextTicket() . "\n";
echo nextTicket() . "\n";Ticket #1 Ticket #2 Ticket #3
Without static, every call would print "Ticket #1".
Checking and removing variables
isset($x)returnstrueif the variable exists and is notnull.unset($x)destroys a variable.var_dump($x)shows both the type and the value, which is perfect for debugging.
<?php
$phone = "0712 345 678";
var_dump(isset($phone));
unset($phone);
var_dump(isset($phone));bool(true) bool(false)
null. Use isset() or the ?? operator to check first.Create a variable called $city holding the text Nakuru.
= "Nakuru";Make the function able to change the global $total.
function add() {
$total;
$total++;
}Make $count keep its value between calls.
function hit() {
$count = 0;
return ++$count;
}
SKOPE