The Wayback Machine - https://web.archive.org/web/20240619071500/https://www.geeksforgeeks.org/php-variables/
Open In App

PHP Variables

Last Updated : 25 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Variables

Variables in a program are used to store some values or data that can be used later in a program. The variables are also like containers that store character values, numeric values, memory addresses, and strings. PHP has its own way of declaring and storing variables. 
There are a few rules, that need to be followed and facts that need to be kept in mind while dealing with variables in PHP:  

  • Any variables declared in PHP must begin with a dollar sign ($), followed by the variable name.
  • A variable can have long descriptive names (like $factorial, $even_nos) or short names (like $n or $f or $x)
  • A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-z’, ‘A-Z’, ‘0-9, and ‘_’) in their name. Even it cannot start with a number.
  • A constant is used as a variable for a simple value that cannot be changed. It is also case-sensitive.
  • Assignment of variables is done with the assignment operator, “equal to (=)”. The variable names are on the left of equal and the expression or values are to the right of the assignment operator ‘=’.
  • One must keep in mind that variable names in PHP names must start with a letter or underscore and no numbers.
  • PHP is a loosely typed language, and we do not require to declare the data types of variables, rather PHP assumes it automatically by analyzing the values. The same happens while conversion. No variables are declared before they are used. It automatically converts types from one type to another whenever required.
  • PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.

Data types used by PHP to declare or construct variables:

  • Integers
  • Doubles
  • NULL
  • Strings
  • Booleans
  • Arrays
  • Objects
  • Resources

Example: 
 

PHP




<?php
  
// These are all valid declarations
$val = 5;
$val2 = 2;
$x_Y = "gfg";
$_X = "GeeksforGeeks";
  
// This is an invalid declaration as it 
// begins with a number
$10_ val = 56; 
  
// This is also invalid as it contains 
// special character other than _
$f.d = "num";  
  
?>


Variable Scopes

Scope of a variable is defined as its extent in a program within which it can be accessed, i.e. the scope of a variable is the portion of the program within which it is visible or can be accessed. 
Depending on the scopes, PHP has three variable scopes: 
 

  • Local variables: The variables declared within a function are called local variables to that function and have their scope only in that particular function. In simple words, it cannot be accessed outside that function. Any declaration of a variable outside the function with the same name as that of the one within the function is a completely different variable. We will learn about functions in detail in later articles. For now, consider a function as a block of statements. 
     

Example: 
 

PHP




<?php
  
$num = 60;
  
function local_var()
{   
    // This $num is local to this function
    // the variable $num outside this function
    // is a completely different variable
    $num = 50;
    echo "local num = $num \n";
}
  
local_var();
  
// $num outside function local_var() is a 
// completely different Variable than that of 
// inside local_var()
echo "Variable num outside local_var() is $num \n";
  
?>


Output: 

local num = 50 
Variable num outside local_var() is 60 
  • Global variables: The variables declared outside a function are called global variables. These variables can be accessed directly outside a function. To get access within a function we need to use the “global” keyword before the variable to refer to the global variable.

Example: 
 

PHP




<?php
  
$num = 20;
  
// function to demonstrate use of global variable
function global_var()
{
    // we have to use global keyword before 
    // the variable $num to access within 
    // the function
    global $num;
      
    echo "Variable num inside function : $num \n";
}
  
global_var();
  
echo "Variable num outside function : $num \n";
  
?>


Output: 
 

Variable num inside function : 20 
Variable num outside function : 20 

Static variable: It is the characteristic of PHP to delete the variable, once it completes its execution and the memory is freed. But sometimes we need to store the variables even after the completion of function execution. To do this we use the static keywords and the variables are then called static variables.  PHP associates a data type depending on the value for the variable.
 

Example: 
 

PHP




<?php
  
// function to demonstrate static variables
function static_var()
{   
    // static variable
    static $num = 5;
    $sum = 2;
      
    $sum++;
    $num++;
      
    echo $num, "\n";
    echo $sum, "\n";
}
  
// first function call
static_var();
  
// second function call
static_var();
  
?>


Output: 

6
3
7
3

You must have noticed that $num regularly increments even after the first function call but $sum doesn’t. This is because $sum is not static, and its memory is freed after the execution of the first function call. 
 

Variable Variables:-

  • PHP allows us to use dynamic variable names, called variable variables.
  • Variable variables are simply variables whose names are dynamically created by another variable’s value.

Example:

PHP




<?php
   $a = 'hello'; //hello is value of variable $a
   $$a = 'World'; //$($a) is equals to $(hello)
   echo $hello; //$hello is World i.e. $hello is new variable with value 'World'
?>


Output:

World

 



Previous Article
Next Article

Similar Reads

React.js Blueprint Variables Font variables
In this article, we will learn about the Font Variables offered by the blueprint.js library. BlueprintJS is a React-based UI toolkit for the web. It is written in Typescript. This library is very optimized and popular for building interfaces that are complex and data-dense for desktop applications that run in a modern web browser. Font Variables: T
3 min read
Less.js Variables Properties as Variables
LESS (Leaner Style Sheets) is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a scripting language that improves CSS and gets compi
3 min read
Less.js Variables Default Variables
LESS (Leaner Style Sheets) is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a scripting language that improves CSS and gets compi
3 min read
PHP | $_FILES Array (HTTP File Upload variables)
How does the PHP file handle know some basic information like file-name, file-size, type of the file and a few attributes about the file which has been selected to be uploaded? Let's have a look at what is playing behind the scene. $_FILES is a two-dimensional associative global array of items which are being uploaded via the HTTP POST method and h
4 min read
How to pass PHP Variables by reference ?
By default, PHP variables are passed by value as the function arguments in PHP. When variables in PHP is passed by value, the scope of the variable defined at function level bound within the scope of function. Changing either of the variables doesn't have any effect on either of the variables. Example: &lt;?php // Function used for assigning new //
2 min read
How to pass variables and data from PHP to JavaScript ?
In this article, let's see how to pass data and variables from PHP to JavaScript. We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to perform the operation on the same page. Else we can pass data from PHP to JavaScript using Cookies. Cookie wo
2 min read
How to pass form variables from one page to other page in PHP ?
Form is an HTML element used to collect information from the user in a sequential and organized manner. This information can be sent to the back-end services if required by them, or it can also be stored in a database using DBMS like MySQL. Splitting a form into multiple steps or pages allow better data handling and layering of information. This ca
4 min read
What are the differences between PHP constants and variables ?
PHP Constants: PHP Constants are the identifiers that remain the same. Usually, it does not change during the execution of the script. They are case-sensitive. By default, constant identifiers are always uppercase. Usually, a Constant name starts with an underscore or a letter which is followed by a number of letters and numbers. They are no need t
2 min read
What are the different scopes of variables in PHP ?
Variable Scopes: The scope of a variable is defined as its extent in the program within which it can be accessed, i.e. the scope of a variable is the portion of the program within which it is visible or can be accessed. Depending on the scopes, PHP has three variable scopes. Local variables: The variables declared within a function are called local
3 min read
How to Assign Multiple Variables in One Line in PHP ?
In PHP, assigning multiple variables in one line can be a handy and efficient way to streamline your code. This technique not only makes your code more concise but also improves readability. There are several approaches to achieve this, each with its own syntax and use cases. Table of Content Using Multiple AssignmentUsing list() FunctionUsing expl
2 min read
Article Tags :