PHP Variables

In this chapter you will learn:

  1. What are variables
  2. Syntax to define variable in PHP
  3. Example - Define PHP variables
  4. PHP Variable substitution in String

Description

A variable is a container holding a certain value.

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

Example

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

Variable Description
$myvar Correct
$Name Correct
$_Age Correct
$___AGE___ Correct
$Name91Correct;
$1Name Incorrect; starts with a number
$Name'sIncorrect; no symbols other than "_" are allowed

Variables are case-sensitive. $Foo is not the same variable as $foo.

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.


<?php/*j a  v a  2 s .c o  m*/
       $name = "java2s.com";
       print "Your name is $name\n";
       $name2 = $name;
       print 'Goodbye, $name2!\n';
?>

The code above generates the following result.

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.

<?php//ja v  a  2  s. c o  m
        $food = "grapefruit";
        print "These ${food}s aren't ripe yet.";
        print "These {$food}s aren't ripe yet.";
?>

The code above generates the following result.

The braces {} tells where the variable ends.

Next chapter...

What you will learn in the next chapter:

  1. Data types in PHP
  2. PHP String
  3. PHP Integer
  4. PHP Float
  5. PHP Boolean
  6. PHP Array
  7. PHP Object
  8. PHP Resource
Home » PHP Tutorial » PHP Introduction
PHP Introduction
PHP Variables