Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Variables in PHP

What is a Variable?

A variable in PHP is a symbol or name that stands for a value. Variables are used to store data that can be manipulated and retrieved throughout your PHP code. The data stored in a variable can change during the execution of the script, hence the name "variable".

Declaring a Variable

In PHP, a variable is declared using the dollar sign ($) followed by the variable name. The name must begin with a letter or an underscore, followed by any number of letters, numbers, or underscores.

Example:

$variableName = value;

Assigning Values to Variables

Values can be assigned to variables using the assignment operator (=). The value can be a number, string, array, object, or any other data type.

Example:

$name = "John Doe";
$age = 30;
$isStudent = true;

Variable Naming Conventions

When naming variables in PHP, follow these rules:

  • Variable names must start with a letter or an underscore.
  • Variable names can only contain letters, numbers, and underscores.
  • Variable names are case-sensitive ($age and $Age are different variables).

Using Variables in PHP

Once a variable is declared and assigned a value, it can be used throughout your PHP code. You can use variables to output data, perform calculations, or as part of conditions.

Example:

$name = "John Doe";
echo "Hello, " . $name . "!";
Output: Hello, John Doe!

Variable Scope

Variable scope refers to the context within which a variable is defined. In PHP, there are three main types of variable scopes:

  • Local Scope: Variables declared within a function are local to that function.
  • Global Scope: Variables declared outside of any function have a global scope and can be accessed anywhere in the script.
  • Static Scope: Static variables exist only in a local function scope but do not lose their value when the program execution leaves this scope.

Global Variables

To access a global variable from within a function, use the global keyword or the $GLOBALS array.

Example:

$x = 10;

function myTest() {
global $x;
echo $x;
}

myTest();
Output: 10

Static Variables

Static variables do not lose their value when the function exits and retain that value if the function is called again.

Example:

function myTest() {
static $x = 0;
echo $x;
$x++;
}

myTest();
myTest();
myTest();
Output: 0
1
2