Students Empire

Learn Something New

Learn PHP

PHP Variable

A variable is a container holding a certain value.

Variable is store the value or information

Syntax :

Variables in PHP beginning with $ followed by a letter or an underscore, then any combination of letters, numbers, and the underscore character.

Here are the rules we would follow to name variables.

  • Variable names begin with a dollar sign ( $ )
  • The first character after the dollar sign must be a letter or an underscore
  • The remaining characters in the name may be letters, numbers, or underscores without a fixed limit

Define PHP variables:

We cannot start a variable with a number. A list of valid and invalid variable names is shown in the following table.

Variable Description
$name Right
$_name Right
$__name_ Right
$name1 Right
$1name Wrong ! Start with number
$name's Wrong ! No symbol other than "_" underscore are allowed

Variables are case-sensitive. $NAME is not the same variable as $name.

                    $txt = "Hello world!";
                    $x = 50;
                    $y = 15.4;

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


            Hello world!

Variable substitution

In PHP we can write variable name into a long string and PHP knows how to replace the variable with its value. Here is a script showing assigning and outputting data.

                   $name = "";
                   print "Your name is $name\n";
                   $name2 = $name;
                   print 'Goodbye, $name2!\n';


            Your name is
            Goodbye, $name2!\n

PHP will not perform variable substitution inside single-quoted strings, and won't replace most escape characters.

In the following example, we can see that:

  • In double-quoted strings, PHP will replace $name with its value;
  • In a single-quoted string, PHP will output the text $name just like that.

                    $food = "grapefruit";
                    print "These ${food}s aren't ripe yet.";
                    print "These {$food}s aren't ripe yet.";


            These fruits aren't ripe yet.These fruits aren't ripe yet.

php variable naming conventions

There are a few rules that you need to follow when choosing a name for your PHP variables.

  • PHP variables must start with a letter or underscore "_".
  • PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
  • Variables with more than one word should be separated with underscores. $my_variable
  • Variables with more than one word can also be distinguished with capitalization. $myVariable