Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

PHP Variables

Variables in PHP

Variables are like a container to store data.
Variables in php starts with Dollar sign ($).

Example:

$a = “Hello”;
$b = 50;
$c = 10.50;
?>

OUTPUT:

Hello
50
10.50

In the above example , there are 3 variables a,b,c which holds values “Hello”,”50″ and”10.50″ respectively.

Rules to declare a variable:

  • A variable starts with the $ sign, followed by the name of the variable
  • 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 ($age and $AGE are two different variables)

Since PHP is a case-sensitive language make sure that your variables are properly used.

Printing the variable:
We use ‘echo’ or ‘print’ keyword to print a variable.

Example:
$a = “easyexamnotes.com”;
echo ” This is $a”;
?>

Scope of Variable:
PHP has three different variable scopes:

  • Local
  • Global
  • Static

Global Variable:

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

Example :
$a = 10; // global scope
function fun() {
// using x inside this function will generate an error
echo “Variable a in the function is: $a

“;
}
fun();
echo “Variable a outside function is: $a

“;
?>

OUTPUT :
Variable a in the function is:
Variable a outside function is: 50

Local Variable:

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

Example
function fun() {
$a = “Hii..”; // local scope
echo “Variable a in the function is: $a

“;
}
fun();
// using a outside the function will generate an error
echo “Variable a outside function is: $a

“;
?>

OUTPUT :
Variable a inside function is: Hii..
Variable a outside function is: