PHP ยท Chapter 6 of 44

PHP Variables

A variable in PHP starts with a dollar sign ($), followed by the variable's name. PHP is a loosely typed language, so you do not need to declare the data type of a variable before using it โ€” PHP figures it out automatically based on the assigned value.

Variable names must start with a letter or underscore, can contain letters, numbers and underscores, and are case-sensitive. Variables can be reassigned to hold different values, even of different types, throughout a script.

Syntax
$variableName = value;

Declaring variables

You create a variable simply by assigning a value to it with the = operator, such as $name = "Amy";. There is no need for a separate declaration step.

Variable scope

A variable declared inside a function is local to that function by default. Variables declared outside any function have global scope and are accessible throughout the top-level script.

Example 1 (php)
<?php
  $name = "Amy";
  $age = 25;
  echo "$name is $age years old.";
?>
Output
Amy is 25 years old.

Variables inside a double-quoted string are automatically replaced by their values.

Example 2 (php)
<?php
  $x = 5;
  $x = "now text";
  echo $x;
?>
Output
now text

PHP variables can change type when reassigned, since PHP is loosely typed.

Key points

  • PHP variables start with a $ sign.
  • You do not need to declare a variable's type.
  • Variable names are case-sensitive.
  • Variables in double-quoted strings are automatically interpolated.
๐Ÿ’ก Note: Use clear, descriptive variable names like $totalPrice instead of vague names like $x to make your code easier to read.

๐Ÿ“ Quick Quiz

1. How does a PHP variable name start?

2. Do you need to declare a variable's type in PHP?

3. Are PHP variable names case-sensitive?