Variable

Variables are "containers" for storing information.


Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the variable:

    
        <?php
            $txt = "Hello world!";
            $x = 5;
            $y = 10.5;

            echo $txt;
            echo "<br>";
            echo $x;
            echo "<br>";
            echo $y;
        ?>
    

Note: When you assign a text value to a variable, put quotes around the value.

Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).


Rules for PHP variables:

  • A variable starts with the $ sign, followed by the name of the variable
  • The value of a variable is the value of its most recent assignment.
  • Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
  • Variables can, but do not need, to be declared before assignment.
  • Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters.
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • Variables used before they are assigned have default values.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different variables)
  • PHP does a good job of automatically converting types from one to another when necessary.
  • PHP variables are Perl-like.


Remember that PHP variable names are case-sensitive!



Output Variables

The PHP echo statement is often used to output data to the screen.

    
        <?php
            $txt = "hello world";
            echo "$txt !";
        ?>
    


The following example will output the sum of two variables:

    
        <?php
            $x = 5;
            $y = 4;
            echo $x + $y;
        ?>