PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<Type JugglingPredefined variables>
view the version of this page
Last updated: Thu, 21 Aug 2003

Chapter 7. Variables

Basics

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]*'

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

<?php
$var = "Bob";
$Var = "Joe";
echo "$var, $Var";      // outputs "Bob, Joe"

$4site = 'not yet';     // invalid; starts with a number
$_4site = 'not yet';    // valid; starts with an underscore
$t銛te = '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.

PHP 4 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. This also means that no copying is performed; thus, the assignment happens more quickly. However, any speedup will likely be noticed only in tight loops or when assigning large arrays or objects.

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:

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

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

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

function test()
{
   return 25;
}

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



add a note add a note User Contributed Notes
Variables
c dot hester at ukonline dot co dot uk
22-Aug-2003 11:23
Here's a simple way to speed up scripts considerably.

I made a page that differs depending on a variable passed in the address. I found that if I checked the variable was blank several times the page took longer to create. Whereas if I set the variable to a default word, the speed jumped from 1.5 seconds to 0.5. (This matched the speed of the page when the variable was defined already by the address.)

Example - the link might be any of these:

test.php?a=page
test.php?a=page&value=yellow
test.php?a=page&value=red

In the first link I left the variable off so the default page appears. I didn't want to add it to the link as it makes the address unnecessarily long. (The page is always accessed from the default link.)

The code used was like this:

if ($value == "") echo "<h1>Default page</h1>";
if ($value == "yellow") echo "<h1>Yellow page</h1>";
if ($value == "red") echo "<h1>Red page</h1>";

I used the variable $value several times in a set of small loops. To speed the page up, all I did was assign the variable at the top of the page like this instead of leaving it blank:

if ($value == "") $value = "default";

Then I amended my code like this:

if ($value == "default") echo "<h1>Default page</h1>";
if ($value == "yellow") echo "<h1>Yellow page</h1>";
if ($value == "red") echo "<h1>Red page</h1>";

I was amazed at the speed increase.
eye of a raven
25-Jun-2003 07:10
jeeez people, why do you always get confused in the simplest things.

here's how referencing works:
to store any value you need a segment of memory.
internally, in machine code the program is just a sequence of numbers. this is also valid for interpreted languages since their parsing engines are compiled executables, so they operate on raw machine code.

so the question is: how does the program 'know' what is what? what programmers call 'variables' are not magical entities in space. they are just places in memory. period. every place in memory has a (duh...) memory address.

the NAME of a variable is a human-readable identifier so that instead of writing raw memory addresses we can use fancy names to denote them.

so, in php:
<?
$foo 
5// "foo" is a name. internally it might be replaced by something like, say 0x3a34b4 which is a memory address in hex notation
$bar// "bar" is also a name. the parser sees no assignment so "$bar" maps to NULL (probably 0x00, dunno...)

$fooReference = &$foo;     //this is a reference assignment. "fooReference" is a name that maps to the same thing as "foo".
$barReference = &$bar//hehe... now what? "barReference" also maps to NULL. but what if $bar is later changed?
?>

references ARE NOT C pointers! a C pointer is an actual variable that stores memory addresses, just like any other variable that stores integers or floats or other.
a reference variable is an ALIAS for a persistent and already existing memory address (that's why there is no copying and that's why you can't assign: $ref = &$(20*4-1) ).

ps. I assume there is another level of indirection between identifiers and actual memory addresses that lets the engine differentiate between foo and fooReference. if not, i suppose the variable names can be treated like C macros?
redshift at pandora dot be
25-Jun-2003 06:36
There are several ways of declaring variabeles. (Sort of like the Dim instruction in vb or asp)

settype($myvar, "string");
(http://be2.php.net/settype)

or

$myvar = (string) "Hello";

Or let php do the hard work for you,

$myvar = "Hello";

It should normally produce the same result...

NOTE:

$myvar = 1; is not the same as $myvar = "1";
Whereas the first would count as an integer, the second as a string. Altough php see trough these things, a database query would not. For example:
odbc_query("INSERT INTO table (number) VALUES(' ".$myvar." ')"); WILL NOT work,
odbc_query("INSERT INTO table (number) VALUES (".$myvar.")"); WOULD work.
damonhastings at yahoo dot com
21-May-2003 06:44
I might mention that stlawson's comment is directly contradicted in Chapter 15: http://www.php.net/manual/en/language.references.php.  References "are not like C pointers, they are symbol table aliases."  And regarding "$a =& $b" it says "that's not $a is pointing to $b or vice versa, that's $a and $b pointing to the same place."

Also, daevid's comment is contradicted in Chapter 15: http://www.php.net/manual/en/language.references.pass.php. (Actually, Daevid's syntax is still legal, but they're phasing it out.)

[Ed. note -- The second comment mentioned above has been removed to help prevent the spread of call-by-reference. :)]
pekka at SPAMphotography-on-theSPAM dot net
30-Apr-2003 02:55
For us newbies:
During developement time you often want to display only some variables on page for debugging.  With this function you can you can save some typing time.

function printvars ($name,$hidden) {
if ($hidden == "1") print "<!-- ";
foreach ($name as $k) {
    global  ${$k};
    print "<br><b>$$k:</b> "  . ${$k};
    }
if ($hidden == "1") print " -->";
return;
}

Use it by first creating an array of variable names (without $'s) you want to display:

$track = array("name","address","car","hobby","favbeer");

and then run the function (use 1 as second parameter if you want to hide the output into html source code):

printvars ($track,0);
phValue at example dot com
04-Mar-2003 10:03
php shows up a var-name conflict if you use the same name for scalar values and arrays:

first we want to use a scalar value:
$scalarValue = 5;
scalarValue holds: 5

But than, you want to use the same name for an array, too,
which seems ok at first glimps:
(sometimes, its hard to find new names for the same purpose..)

$scalarValue = array();
array_push($scalarValue,3);

scalarValue[0] holds: 3

now, all seems ok, since the array assignment went well..
but, where is the scalarValue gone, if we ask for it?
if you echo for it, you ask for the array:
scalarValue holds: $Array
The scalar value has no longer a reference, since it shares the
same name with an array..
such a bug can give you some hard time to dig for!
unleaded at nospam dot unleadedonline dot net
15-Jan-2003 10:37
References are great if you want to point to a variable which you don't quite know the value yet ;)

eg:

$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:

test
gabriel at bumpt dot net
14-Jan-2003 01:26
I know this is not a C++ newsgroup, but I just wanted to get things right, after the comment of "someone at somewhere dot com".

The C-like piece of code provided by stlawson DOES use a pointer, and NOT a C++ reference. "someone at somewhere dot com" got confused because type declaration was obviously omitted for clarity reasons. A reference in C++ is almost a type qualifier: a variable is of type "reference to objects of class MyClass". Therefore, one cannot assign &myObj to a variable declared as a "reference to objects of class MyClass". &myObj really identifies a pointer to myObj, and dereference (using * or ->) is requiered.
someone at somewhere dot com
23-Dec-2002 03:50
The comment from stlawson AT sbcglobal DOT net about the C/C++ isn't quite correct:

You confuse the pointer notation of C/C++ with the reference notation only availible in C++...

True, dreferencing has to be manually done if you use the pointer notation, but not if you use the reference notation...
stlawson AT sbcglobal DOT net
06-Jul-2002 08:47
In 'ghent's comment on the 'above example' I think he confuses the confusion ;)

Here is the example referred to:

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

eference $foo via $bar?lter $bar? IS correct, but it is a little obscure.  Here what it means:

$bar is assigned a reference to $foo, thus $bar eferences?or points to $foo which contains the string ob?  Essentially what is happening here is ob?is stored in memory at a particular address.  &$foo returns that address [where ob?is stored].  That address is assigned to $bar.  So, in the string y name is $bar? $bar ses?the address it contains to find ob?(which is n?$foo) and thus the string becomes y name is Bob?  When the string is assigned to $bar, because $bar refers to $foo, it gets assigned to the same address location that ob?is stored at, thus ob?is overwritten by y name is Bob?  The trick here is to realize that $bar behaves as if it is $foo, so when something is assigned to $bar (the alias of $foo), it as if it was being assigned to $foo!

After the above script is run, the output will look like this:

  My name is BobMy name is Bob

e.g. both $foo and $bar print the same thing.

In ++?the same code snippit would look like this:

foo = ob?;
bar = &foo ;
bar = y name is ?+ *bar ;

Notice that in C/C++ it is necessary to manually dereference the pointer (*bar) ?PHP does this automagically.

BTW: You might think that cho $bar;?would display the address of $foo ?not so!  More PHP automagic ;)
isaac at chexbox dot com
14-Apr-2002 10:21
<<------------------< Env. Variables >------------------>
If you are looking for an explanation of environment variables, go to
http://www.php.net/manual/en/language.variables.external.php

If you wanted to set environment variables, look into the putenv() function.
http://www.php.net/manual/en/function.putenv.php
cd579 at hotmail dot com
06-Apr-2002 04:16
Another way to assign a variable a large amount text without having to worry about quotes getting in the way is like so:

$aVariable = <<<END
"HEY!"
END;

print "$aVariable";

output:  "HEY!"

Where as this is will produce an error:
$aVariable = ""HEY!"";
engard at all dot NOSPAM dot hu
01-Mar-2002 12:06
Actually, you can use other chars (including spaces) in the variable name, if you are using variable variables. E.g., the following works for me (in PHP 4.1.1):

$x="blah blah-blah";
$$x="value";
echo "var==" . $$x;
echo "var==" . ${"blah blah-blah"};

Its output is:
var==value
var==value

You can use it also in object variables (properties).
webmaster at webpagebydesign dot com
08-Dec-2001 11:12
a great way to pass variables from page to page... http://www.php.net/manual/phpfi2.php
select: How PHP/FI handles GET and POST method data
ie:
    /cgi-bin/php.cgi/file.html?abc+def+EMAIL_ADDR=rasmus@lerdorf.on.ca&var=value
The relevant components of the PHP symbol table will be:

    $argc       = 4
    $argv[0]    = abc
    $argv[1]    = def
    $argv[2]    = EMAIL_ADDR=rasmus@lerdorf.on.ca&var=value
    $EMAIL_ADDR = rasmus@lerdorf.on.ca
    $var        = value
dwood at templar dot com
25-Apr-2001 01:31
I had trouble digging this out, and searches for various terms (memory model, garbage collection, &c) were not productive.
<P>
PHP4 uses reference counting for garbage collection. Details about this system can be found here:
<P>
http://www.zend.com/zend/art/ref-count.php
risa4 at law dot leidenuniv dot nl
23-Mar-2001 08:31
If, for some reason you need to declare
a dynamic variable global, say $usertype1, $usertype2 etc...
do it like this:
                $i=1;
                $ready=#number of
                        generated
                        variables#
         while ($i < $ready) {

        $var="usertype$i";
        global $$var;
       
                ###do the action with
                   the var, for
                   example:##
                echo $$var;
        $i++;
        }

<Type JugglingPredefined variables>
 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: http://php.mirrors.ilisys.com.au/
Last updated: Sat 01 Nov 2003 04:13:36 EST EST