Code has been added to clipboard!

PHP Variable Explained: Learn How to Use It

Reading time 4 min
Published May 6, 2019
Updated Oct 2, 2019

After you learn PHP basics, you will see dollar signs not only in your dreams but also on your screen, as this symbol ($) is used to mark variables. A PHP variable is similar to a little container that is used to store information (value). A value usually consists of letters or numbers, but a variable can also exist without storing any value.

You are not required to declare a variable before adding a value to it. The first time you assign a value to a particular variable name, you create a variable. The value is assigned by using the equal sign, also called the assignment operator (=). Repetition of the process with the same name results in a change of value.

PHP will also automatically understand the type of the variable according to the value you have assigned to it. The context in which a particular PHP variable works is called PHP variable scope.

PHP Variable: Main Tips

  • PHP variables start with a $ sign.
  • PHP variables are used to store information (value).
  • The name of a variable can begin with a letter or an underscore character (_), but never a number. However, it may contain numbers.
  • Variables are case-sensitive.

What a Variable Is

A PHP variable may have a name as long or short as you wish. It can consist of one letter (x, y, z, and so on) or a whole bunch of them (tree, household, thelongestwordinthewholewideworld).

The example below shows that the variable $text is a container to the value of Hey coders! and both $xand $y variables hold their respective values of 9 and 1.

Example
<?php  
  $text = "Hey coders!";  
  $x = 9;
  $y = 1;  
?>

Note: In order to assign text to a variable correctly, quotes are used. They are not needed for numerical values.

Way to Output

If you wish to output the information to the screen, it's easy to do by using an echo statement. In the example below, you can see a PHP variable being used in the echo statement. The result will be the output of both statement text and the value that has been assigned to the $website variable.

Example
<?php
  $website = "bitdegree.org";  
  echo "I want to visit $website!";
?>

The Scope

The user can declare variables anywhere in the PHP script, outside of a function or within one. The exact part in which a certain variable can be used is called PHP variable scope. There are three main scopes:

  • Local
  • Global
  • Static

Local vs. Global

By expressing a PHP variable outside the function, you make it a PHP Global variable. This means that a certain variable can be used anywhere outside the function.

Example
<?php
  $x = 10// global scope
 
  function learnTest() {
    // using x inside this function will generate an error
    echo "The x inside function is: $x";
  } 
  learnTest();

  echo "The x outside function is: $x";
?>

If you express a variable inside the function, it gives it a Local variable scope. As the name suggests, this PHP variable will be only usable locally: inside that particular function.

Example
<?php
  function learnTest() {
    $x = 9// local scope
    echo "Variable x inside function is: $x";
  } 
  learnTest();

  // using x outside the function will generate an error
  echo "Variable x outside function is: $x";
?>

Note: Different variables with local PHP variable scopes can have identical names and still be executed correctly if they are used within different functions.

Global

If you wish to use a PHP global variable inside a certain function, you should use the keyword global in front of the variable. In the example below you can see how PHP variables $x and $y are used inside a function called learnTest().

Example
<?php
  $x = 10;
  $y = 10;

  function learnTest() {
    global $x, $y;
    $y = $x + $y;
  }

  learnTest();
  echo $y; // outputs 20
?>

Global variables are stored in a $GLOBALS[index] array. These variables can be accessed and updated without leaving the function. This example illustrates how it works in the learnTest() function:

Example
<?php
  $x = 20;
  $y = 10;

  function learnTest() {
    $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
  } 

  learnTest();
  echo $y; // outputs 30
?>

Static

A local PHP variable scope also indicates that after a certain function is done, the variables inside are deleted. Sometimes, we might prefer to keep them longer.

For a local variable to stay after the function is executed, a static keyword must be used when declaring it. You can see an example of how it is applied on the PHP variable $x below.

Example
<?php
  function learnTest() {
    static $x = 0;
    echo $x;
    $x++;
  }

  learnTest();
  learnTest();
?>

The variable will keep both its local scope and the data it held before. It will not be deleted, no matter how many times you will repeat the function.

PHP Variable: Summary

  • You can recognize a PHP variable from a first glance, as it always starts with a $. While it's name can contain numbers, it cannot start with one: the first symbol must be either a letter or an underscore (_).
  • Information stored in a certain PHP variable is called value.
  • Unlike functions, variables are case-sensitive.
Tutorial
Introduction
Installation
Syntax
Variable
Superglobals
Data Types
String
Array
Multidimensional Array
Sort Array
Constant
Operators
Cookies
Sessions
DateTime
Error Handling
Exception Handling
File
Write and Create File
File Open, Read and Close
File Upload
Filtering
Redirecting
Advanced Filters
Forms
Form Required Field
Validate Email/URL
Form Validation
Form Action
Function
Prepared Statements
JSON
Calendar
ZIP File
FTP
HTTP Response
DateTime Functions
Error Functions
File Function
Filter
Math Functions
Mail Function
Miscellaneous Functions
Date Format
String Functions
Array Functions
Directory Functions
MySQL Database
MySQL Connection
MySQL Create Database
MySQL Create Table
MySQL Delete Data
MySQL Insert Data
MySQL Get Last Record ID
MySQL Insert Multiple Records
MySQL Select Data
MySQL Limit Data
MySQL Update Data
MySQLi Functions
AJAX and MySQL
AJAX Search
AJAX Poll
RSS Reader
Read XML File in PHP
XML Parser
SimpleXML Parser
SimpleXML: Node and Attribute
Expat XML Parser
DOMDocument
Libxml Functions
SimpleXML Functions
XML Parsing Functions
PHP isset
PHP echo and print
PHP if else and elseif
PHP switch case
PHP include File
PHP while Loop
PHP for and foreach
PHP mail()
PHP explode()
PHP substr()
PHP str_replace()
PHP array_push
PHP count()