PHP Variables

A variable can be considered to be a sort of container to store some value or information, just like we use a bucket or drum to store water! At times, there is a need to store some values or information for future usage in programming. For this purpose we use variables.

In PHP a variable name starts with the dollar sign($) followed by its name. For example – $x, $y, $car, $myname etc.

Declaration of Variables in PHP –

Unlike other programming languages, variables in PHP need not to be declared before usage. In PHP a variable is declared at the moment a value is assigned to it.

For Example –

<?php
    $x = 4;
    $mytext = "Hello World";
?>

When the above script executes, the variable x will store the value 4 and the variable mytext will store the text “Hello World”.

Values are assigned to a variable by the equal to ( = ) sign (called as assignment operator). Variable name is written on the left hand side and the value on the right hand side.

Note: In programming, assignment means to store some value inside a variable. In most of the programming languages, assignment occurs from right to left. That means the varibale is written on the left hand side whereas the value  should be written on the right hand side.

Naming Conventions –

A variable name can be anything, a letter, a word (but not a reserved keyword). There are however some rules to create variables in PHP.

  • Every variable name must start with the dollar sign ($).
  • A variable name can only contain alphanumeric characters, numbers (number should not be at the beginning) and underscores.
  • A variable name must start with a letter or with an underscore.
  • A variable name cannot start with a number.
  • A variable name cannot contain spaces.

Note: In PHP a variable name is case sensitive. For instance, $x and $X are not the same but are two different variables.

Variable Output in PHP –

The ‘echo’ statement in PHP is most often used to output a data on the screen. The below example will output the value of variable x.

<?php
    $x = 10;
    echo $x;
?>

Output

10

The value of a variable can be overwritten

The value a variable holds is the value it is assigned recently. For example –

<?php
    $x = 10;
    $x = 5;
    echo $x;
?>

Output

5

In above script the final value that the variable x will hold is 5. X was holding a value of 10. But that value has been replaced with 5.