PHP Variables
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 |
$Name91 | Correct; |
$1Name | Incorrect; starts with a number |
$Name's | Incorrect; 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/*ww w . j a va2 s .co 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//w w w. ja v a 2s . 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.