Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Language Reference : Variables

Chapter 3. Variables


Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'


For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).


You may also want to take a look at the Appendix T, Userland Naming Guide.

For information on variable related functions, see the Variable Functions Reference.

= 'Bob';
$Var = 'Joe';
"$var, $Var";      // outputs "Bob, Joe"

$4site = 'not yet';     // invalid; starts with a number
$_4site = 'not yet';    // valid; starts with an underscore
$täyte = 'mansikka';    // valid; 'ä' is (Extended) ASCII 228.

In PHP 3, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.

As of PHP 4, PHP offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:

= 'Bob';              // Assign the value 'Bob' to $foo
$bar = &$foo;              // Reference $foo via $bar.
$bar = "My name is $bar";  // Alter $bar...
echo $bar;
$foo;                 // $foo is altered too.

One important thing to note is that only named variables may be assigned by reference.

= 25;
$bar = &$foo;      // This is a valid assignment.
$bar = &(24 * 7);  // Invalid; references an unnamed expression.

function test()

$bar = &test();    // Invalid.

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type - FALSE, zero, empty string or an empty array.

Example 3.1. Default values of uninitialized variables

echo ($unset_bool ? "true" : "false"); // false
$unset_int += 25; // 0 + 25 => 25
echo $unset_string . "abc"; // "" . "abc" => "abc"
$unset_array[3] = "def"; // array() + array(3 => "def") => array(3 => "def")

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

Related Examples ( Source code ) » language.variables

Code Examples / Notes » language.variables

carel solomon

You can also construct a variable name by concatenating two different variables, such as:
$arg = "foo";
$val = "bar";
//${$arg$val} = "in valid";     // Invalid
${$arg . $val} = "working";
echo $foobar;     // "working";
//echo $arg$val;         // Invalid
//echo ${$arg$val};     // Invalid
echo ${$arg . $val};    // "working"

giunta dot gaetano

With php 5.1.4 (and maybe earlier?) take care about not using $this as a variable name, even when in the global scope or inside a plain function: the engine will prevent assigning any value to it...


When using variable variables this is invalid:
$my_variable_{$type}_name = true;
to get around this do something like:
${$n} = true;
(or $$n - I tend to use curly brackets out of habit as it helps t reduce bugs ...)


what is so simple and flexible about these variable..? They're all the same thing -.-"
$var = whatever;
in fact is more complicated than:
String HelloWorld = hello;

chris hester

Variables can also be assigned together.
$a = $b = $c = 1;
echo $a.$b.$c;
This outputs 111.


Simple sample and variables and html "templates":
The PHP code:
$SYSN["title"] = "This is Magic!";
$SYSN["HEADLINE"] = "Ez magyarul van"; // This is hungarian
$SYSN["FEAR"] = "Bell in my heart";
The template:

This is simple, quick and very flexibile


References are great if you want to point to a variable which you don't quite know the value yet ;)
$error_msg = &$messages['login_error']; // Create a reference
$messages['login_error'] = 'test'; // Then later on set the referenced value
echo $error_msg; // echo the 'referenced value'
The output will be:


References and "return" can be flakey:
//  This only returns a copy, despite the dereferencing in the function definition
function &GetLogin ()
return $_SESSION['Login'];
//  This gives a syntax error
function &GetLogin ()
return &$_SESSION['Login'];
//  This works
function &GetLogin ()
$ret = &$_SESSION['Login'];
return $ret;


pay attention using spaces, dots and parenthesis in case kinda like..
$var=($number>0)?1.'parse error':0.'here too';
the correct form is..
$var=($number>0)?1 .'parse error':0 .'here too';
$var=($number>0)?(1).'parse error':(0).'here too';
$var = ($number > 0) ? 1 . 'parse error' : 0 . 'here too';
i think that's why the parser read 1. and 0. like decimal numbers not correctly written, point of fact
$var=$number>0?1.0.'parse error':0.0.'here too';
seems to work correctly..

ludvig dot ericson

On the previous note:
This is due to how evaluation works. PHP will think of it as:
$a = whatever $b = $c is
$b = whatever $c = 1 is
... because an expression is equal to what it returns.
Therefore $c = 1 returns 1, making $b = $c same as $b = 1, which makes $b 1, which makes $a be $b, which is 1.
$a = ($b = $c = 1) + 2;
Will have $a be 3 while $b and $c is 1.
Hope that clears something up.


OK how about a practicle use for this:
You have a session variable such as:
$_SESSION["foo"] = "bar"
and you want to reference it to change it alot throughout the program instaed of typing the whole thing over and over just type this:
$sess =& $_SESSION
$sess['foo'] = bar;
echo $sess['foo'] // returns bar
echo $_SESSION["foo"] // also returns bar
just saves alot of time in the long run
also try $get = $HTTP_GET_VARS
or $post = $HTTP_POST_VARS

mike fotes

In conditional assignment of variables, be careful because the strings may take over the value of the variable if you do something like this:
$condition = true;
// Outputs " <-- That should say test"
echo "test" . ($condition) ? " <-- That should say test" : "";
You will need to enclose the conditional statement and assignments in parenthesis to have it work correctly:
$condition = true;
// Outputs "test <-- That should say test"
echo "test" . (($condition) ? " <-- That should say test " : "");


In addition to what jospape at hotmail dot com and ringo78 at xs4all dot nl wrote, here's the sintax for arrays:
//considering 2 arrays
$foo1 = array ("a", "b", "c");
$foo2 = array ("d", "e", "f");
//and 2 variables that hold integers
$num = 1;
$cell = 2;
echo ${foo.$num}[$cell]; // outputs "c"
$num = 2;
$cell = 0;
echo ${foo.$num}[$cell]; // outputs "d"


Here's a simple solution for retrieving the variable name, based on the lucas ( solution, but shorter, just two lines =)
function var_name(&$var, $scope=0)
   $old = $var;
   if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key;  


Here's a pair of functions to encode/decode any string to be a valid php and javascript variable name.
function label_encode($txt) {
 // add Z to the begining to avoid that the resulting
 // label is a javascript keyword or it starts with a
 // number
 $txt = 'Z'.$txt;
 // encode as urlencoded data
 $txt = rawurlencode($txt);
 // replace illegal characters
 $illegal = array('%', '-', '.');
 $ok = array('é', 'è', 'à');
 $txt = str_replace($illegal,$ok, $txt);
 return $txt;
function label_decode($txt) {
 // replace illegal characters
 $illegal = array('%', '-', '.');
 $ok = array('é', 'è', 'à');
 $txt = str_replace($ok, $illegal, $txt);
 // unencode
 $txt = rawurldecode($txt);
 // remove the leading Z and return
 return substr($txt,1);

lucas dot karisny

Here's a function to get the name of a given variable.  Explanation and examples below.
 function vname(&$var, $scope=false, $prefix='unique', $suffix='value')
   if($scope) $vals = $scope;
   else      $vals = $GLOBALS;
   $old = $var;
   $var = $new = $prefix.rand().$suffix;
   $vname = FALSE;
   foreach($vals as $key => $val) {
     if($val === $new) $vname = $key;
   $var = $old;
   return $vname;
The problem with figuring out what value is what key in that variables scope is that several variables might have the same value.  To remedy this, the variable is passed by reference and its value is then modified to a random value to make sure there will be a unique match.  Then we loop through the scope the variable is contained in and when there is a match of our modified value, we can grab the correct key.
1.  Use of a variable contained in the global scope (default):
 $my_global_variable = "My global string.";
 echo vname($my_global_variable); // Outputs:  my_global_variable
2.  Use of a local variable:
 function my_local_func()
   $my_local_variable = "My local string.";
   return vname($my_local_variable, get_defined_vars());
 echo my_local_func(); // Outputs: my_local_variable
3.  Use of an object property:
 class myclass
   public function __constructor()
     $this->my_object_property = "My object property  string.";
 $obj = new myclass;
 echo vname($obj->my_object_property, $obj); // Outputs: my_object_property


As with echo, you can define a variable like this:
$text = <<<END
The closing END; must be on a line by itself (no whitespace).


As an addendum to David's 10-Nov-2005 posting, remember that curly braces literally mean "evaluate what's inside the curly braces" so, you can squeeze the variable variable creation into one line, like this:
 ${"title_default_" . $title} = "selected";
and then, for example:
 $title_select = <<<END
   <select name="title">
     <option $title_default_Mr  value="Mr">Mr</option>
     <option $title_default_Ms  value="Ms">Ms</option>
     <option $title_default_Mrs value="Mrs">Mrs</option>
     <option $title_default_Dr  value="Dr">Dr</option>

raja shahed

$name = "Christine_Nothdurfter";
// not Christine Nothdurfter
// you are not allowed to leave a space inside a variable name ;)
$$name = "'s students of Tyrolean language ";
print " $name{$$name}
print  "$name$Christine_Nothdurfter";
// same


// I am beginning to like curly braces.
// I hope this helps for you work with them
for ($varname = sprintf("filename%d",$i);   isset  ( ${$varname} ) ;   $varname = sprintf("filename%d", $i)  )  {
echo "${$varname}
$varname = sprintf("filename%d",$i);


> Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' not quite true. You can, in fact, only declare variables having a name like this if you use the syntax <?php $varname = "naks naks"; ?>.. but in fact a variable can have moreless any name that is a string... e.g. if you look at an array you can have
.. by accessing the variables-namespace via {} you can have the same functinalities for all variables, e.g.
<?php ${''} = "my empty variable"; ?>
is a valid expression and the variable having the empty string as name will have the value "my empty variable".
read the chapter on "variable variables" for further information.


$id = 2;
$cube_2 = "Test";
echo ${cube_.$id};
// will output: Test

Change Language

Follow Navioo On Twitter
Basic syntax
Control Structures
Classes and Objects (PHP 4)
Classes and Objects (PHP 5)
References Explained
eXTReMe Tracker