Skip to main content

PHP Variables

PHP is a popular scripting language widely used for web development. It is server-side, meaning that it runs on the server before it is sent to the user's browser. This tutorial will guide you through one of the basic but essential aspects of PHP, which is 'PHP Variables'.

What are Variables?

In PHP, a variable is a name given to a memory location that stores data. It is a way to store information that can be used later by the program. For example, a variable could be created that holds the user's name, their age, or any other information we want to store and use.

Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable. Here is an example:

<?php
$myVariable = "Hello, World!";
echo $myVariable;
?>

In the above example, $myVariable is a variable. This variable is assigned the string value "Hello, World!". echo is used to output the value of the variable.

PHP Variable Naming Rules

Here are the rules for naming PHP variables:

  • A variable name must start with a letter or the underscore character (_)
  • A variable name cannot start with a number
  • A variable name can only contain alphanumeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($myVariable and $myvariable are two different variables)

Example:

<?php
$_myVariable1 = "Hello, World!";
$myVariable2 = 123;
echo $_myVariable1;
echo $myVariable2;
?>

PHP Variables are Loosely Typed

One of the key things to remember about PHP is that it's a loosely typed language. This means you don't have to declare the data type of a variable when you create one. PHP automatically converts the variable to the correct data type, depending on its value.

Example:

<?php
$myVariable = "Hello, World!"; //string
$myVariable = 123; //integer
?>

PHP Variable Scope

In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes:

  • Local
  • Global
  • Static

We'll cover these in more detail in a future tutorial.

Hopefully, this tutorial has given you a solid introduction to PHP variables. Practice creating and using variables in your PHP scripts, and you'll soon become comfortable with them. Remember, they're one of the most fundamental aspects of the language, and they're used constantly in all but the simplest scripts.