๐ŸŽ“ A1Learner
๐Ÿ”

PHP Variables

A variable is a named box that holds a value. The value in the box can change while the program runs.

Make a variable and print it

The first line stores text in $name. The second line prints the stored value.

<?php
$name = "Hana";
echo $name, "\n";

Change the value

The name stays the same here. A new value replaces the old one, and the second print shows it.

<?php
$name = "Hana";
echo $name, "\n";
$name = "Mina";
echo $name, "\n";

Add two variables

Two variables hold numbers here. A third variable holds their sum.

<?php
$apples = 4;
$pears = 3;
$total = $apples + $pears;
echo $total, "\n";

Case makes two names

The names $name and $Name differ only in case. PHP treats them as two different variables.

<?php
$name = "Hana";
$Name = "Mina";
echo $name, "\n";
echo $Name, "\n";

Example

<?php
$name = "Hana";
$age = 30;
echo "Name: ";
echo $name, "\n";
echo "Age: ";
echo $age, "\n";

Key points

  • Every variable name starts with a $ sign.
  • A name starts with a letter or an underscore after the $ sign.
  • Letters, numbers and underscores can follow the first character of a name.
  • No type is declared for a variable.
  • PHP works out the type of a variable from its value.
  • Variable names are case sensitive, and keywords are not.
  • A variable holds a value under a name, so the program can use that value by its name.

In this example, $name holds the text Hana. $age holds the number 30. A label prints before each value, so the name and the age sit on labelled lines.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

Which line stores the number 5 in a variable named count?