PHP Variable

A variable is a name given to a memory location which stores some data.



  • Each variable name must be started after using a dollar sign ($).
  • The name must be started with an alphabet or an underscore (_).
  • It may contain only alpha- numeric characters and underscores.
  • No space is allowed. Two words can be separated using underscore.
  • Variable names are case- sensitive.
Valid names- $var, $_var, $my_var, $MyVar, $variable345

Invalid names- $7var, $var%, $my var



  • There is no syntax for declaring a variable; therefore there is no need to declare a variable before using it.
  • No datatype is declared for a variable in php. Any variable can contain any type of value.
  • If a variable is used without assigning it a value, it will show an error.
  • <!DOCTYPE html>
    <html>
    <body>
    <?php
    $var1=35;$var2=45;
    $sum=$var1+$var2; //Adding the two variables.
    echo "The sum of ".$var1." and ".$var2." is ".$sum;
    ?>
    </body>
    </html>

    Output



  • In above example, two variables var1 and var2 are created with values 35 and 45 respectively. A third variable sum is created and the addition of var1 and var2 is assigned to it. The variable sum is printed using echo statement. Read echo in PHP-Displaying Output.



  • The scope is the accessibility of the variables. It tells where a variable can be accessed from. The scope can be of two types-
  • 1.Local- The accessibility of the variable is limited to a particular block or function.

    2.Global- The variable can be accessed from anywhere in the document and from any function.

    It can be understood by the following example-

    <?php
    $a=10;
    function display()
    {
    echo "Inside the function<br>";
    $a=20;
    echo "a= ".$a."<br>";
    $b=30;
    echo "b= ".$b."<br>";
    }
    display();
    echo "Outside the function<br>";
    echo "a= ".$a."<br>";
    echo "b= ".$b."<br>";
    ?>

    Output



    • In above example, a variable a is created outside the functions so it can be used from anywhere in the code. When the function display() is called, the function creates a local variable a and prints it. Then it creates a new local variable b, assigns it a value and prints it.
    • Then a is directly printed from outside of the function and it prints the global value of this variable. But when we tried to print b, it displayed an error because b is not a global variable but it was created locally in the function display().
    • Note: You can also use the keyword global to access a global variable from a block.
      • Example

        <?php

        $a=10;

        function display()

        {

        global $a;

        }

        Read functions in Functions.