+91 9952732367

PHP Variables

4. PHP Variables:

A variable in programming is used to store the information. Variables can represent numeric values, characters, character strings.

In PHP variables all start with a dollar sign ($).


//PHP has no command to declaring a variable

$x = "s3learn";

//Variable $x set to a string value (s3learn)

$y = 1;

//Variable $y set to a numeric value (1)

$z= 1+2;

//Variable $z equal to 3 or (1+2)

$a= 1+$z;

//Variable $a equal to 4 or (1+ (1+2))

$b= $x.$y;

//[.] Combine both values. $b equal to s3learn1 or (“s3learn”.1)


PHP is a loosely type language

  •  In the above example, we did not have to tell PHP which data type the variable is like in other languages such as C, C++ and Java.

Rules for PHP Variables:

  • A variable name must start with $ sign.
  • Variable names are case sensitive.
  • A variable name must start with a letter or underscore (_) character.
  • A variable name cannot start with a number.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).

Scope of the variables in PHP:

  • The scope of a variable is the context within which it is defined.

PHP has three different variable scopes:

  • Local
  • Global
  • Static
 $x=0;     // global scope

function  test()


echo 'X value: '.$x.'<br/>';

global $x;

$y=0;     // local scope

Static $z=0; // static scope




echo 'X value: '.$x.', Y value:'.$y.', Z value:'.$z.'<br/ >';


echo 'X value: '.$x.'<br/>';

echo 'Y value: '.$y.'<br/>';

echo 'Z value: '.$z.'<br/>';




Out Put is:

X value: 0

Y value:

Z value:

X value:

X value: 1, Y value:1, Z value:1

X value:

X value: 2, Y value:1, Z value:2

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.

The global keyword is used to access a global variable from within a function.

A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

Copyright © s3learn.com