PHP Variables

Variables are named containers that store data such as numbers, text, or arrays so you can reuse and change that data throughout your script.

In PHP every variable name begins with a dollar sign ($) followed by the name. You create a variable simply by assigning a value to it with the equals sign; there is no separate declaration step. From that moment the name holds the value until you change it or the script ends.

Creating variables of different types

<?php
$name = "Aisha";      // a string
$age = 29;             // an integer
$height = 1.68;        // a float
$isMember = true;      // a boolean

echo $name . " is " . $age . " years old.";
?>

Naming rules

PHP is strict about how variable names are formed. Following these rules keeps your code valid and readable. Note that variable names are case-sensitive, so $total and $Total refer to two completely different variables.

  • A name must start with a letter or an underscore, never a digit.
  • After the first character it may contain letters, digits, and underscores.
  • No spaces or special characters such as - or % are allowed.
  • Names are case-sensitive: $count and $Count are distinct.

PHP is loosely typed

You do not tell PHP what kind of value a variable will hold; it works that out from the value you assign. You can even reassign a variable to a different type later, though doing so can make code harder to follow. Use the var_dump function when you want to see the exact type and value PHP is storing.

Reassigning and inspecting a variable

<?php
$data = 42;
var_dump($data);      // int(42)

$data = "forty-two";
var_dump($data);      // string(9) "forty-two"
?>
ExampleValid?Reason
$firstNameYesStarts with a letter
$_totalYesStarts with an underscore
$2ndPlaceNoCannot start with a digit
$user-nameNoHyphen is not allowed
Note: PHP assigns most values by copy. When you write $b = $a, changing $b afterwards does not affect $a, because $b received its own copy of the value.
Note: Choose descriptive names like $totalPrice instead of $tp. Clear names act as documentation and reduce the need for extra comments.

Exercise: PHP Variables

What symbol must come before every PHP variable name?