In programming, a variable is a value that can be changed. All variables will have a storage location and a name. The variable name is usually used to refer the value that is stored in a variable.

Declaring variables in PHP

In PHP, variables are denoted with a $ symbol preceding the variable name.

Example

<?php
$a = "Hello world!";
$x = 5;
$y = 10.5;
$z = 'a';
?>

Things to remember

  • PHP automatically converts variables from one type to another.
  • A variable will have a value of it’s most recent assignment.
  • Variables do not need to be declared before assigning a value.
  • Values are assigned to a variable using the = operator.
  • A variable name cannot start with a number.
  • Variable names are case-sensitive.
  • When assigning text to a variable, put the value in a quote.

Scope of a variable

The scope of a variable refers to the accessible range of a variable in a program. In PHP, there are mainly two different variable scopes.

  • Local –  The variable is only accessible within the function that created it.

Example

<?php
$a = 1; /* global scope */ 
function localVar()

$a=10;
    echo "The local variable a has value: $a"; /*local scope variable */ 

localVar();
echo "The global variable a has the value: $a";
?>

The above program when executed will produce the following output.

The local variable a has value: 10
The global variable a has the value: 1
  • Global – A global variable can be accessed from anywhere in the program. To access a global variable in a function, you should use global keyword.

Example

<?php
$a = 1;
$b = 2;

function my_function()
{
    global $a;
$b=5;
echo "The value of a is $a";
echo "The value of b is $b";

my_function();
echo "I am having the value $b";
?>

The above program when executed will produce the following output.

The value of a is 1
The value of b is 5 I am having the value 2