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

Hoofdstuk 8. 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]*'

Opmerking: 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�yte = 'mansikka';    // valid; '�' is 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.
?>

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' { ord('Z') == 90, ord('[') == 91 ).

Voorbeeld 8-1. Arithmetric Operations on Character Variables

<?php
$i = 'W';
for($n=0; $n<6; $n++)
  echo ++$i . "\n";

/*
  Produces the output similar to the following:

X
Y
Z
AA
AB
AC

*/
?>



User Contributed Notes
Variables
add a note add a note
risa4 at law dot leidenuniv dot nl
23-Mar-2001 11: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++;
}

dwood at templar dot com
24-Apr-2001 06:31

I had trouble digging this out, and searches for various terms (memory model, garbage collection, &c) were not productive.


PHP4 uses reference counting for garbage collection. Details about this system can be found here:



webmaster at webpagebydesign dot com
08-Dec-2001 02:12

a great way to pass variables from page to page...
select: How PHP/FI handles GET and POST method data
ie:
  /cgi-bin/php.cgi/[email protected]&var=value
The relevant components of the PHP symbol table will be:

   $argc     = 4
   $argv[0]    = abc
   $argv[1]    = def
  $argv[2]    = [email protected]&var=value
  $EMAIL_ADDR = [email protected]
   $var        = value

engard at all dot NOSPAM dot hu
01-Mar-2002 03: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).

cd579 at hotmail dot com
06-Apr-2002 09: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!"";

isaac at chexbox dot com
14-Apr-2002 03:21

<<------------------< Env. Variables >------------------>
If you are looking for an explanation of environment variables, go to


If you wanted to set environment variables, look into the putenv() function.

stlawson AT sbcglobal DOT net
06-Jul-2002 01: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.
?>

�Reference $foo via $bar�/�Alter $bar�� IS correct, but it is a little obscure.  Here�s what it means:

$bar is assigned a reference to $foo, thus $bar �references� or points to $foo which contains the string �Bob�.  Essentially what is happening here is �Bob� is stored in memory at a particular address.  &$foo returns that address [where �Bob� is stored].  That address is assigned to $bar.  So, in the string �My name is $bar�, $bar �uses� the address it contains to find �Bob� (which is �in� $foo) and thus the string becomes �My name is Bob�. When the string is assigned to $bar, because $bar refers to $foo, it gets assigned to the same address location that �Bob� is stored at, thus �Bob� is overwritten by �My 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�s 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 �C++� the same code snippit would look like this:

foo = �Bob� ;
bar = &foo ;
bar = �My 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 �echo $bar;� would display the address of $foo � not so!  More PHP automagic ;)

r dot yaker at wiredfusion dot net
18-Aug-2002 04:01

If you use global variables within a function, take note that changing the variable keyword from "global", somewhere down the line, to "return", that that variable can either be one or the other. It can't be both "returned" and "global".

So, if within a function you have on line x:
global $var;

and then on line x+1:
return $var;

that $var becomes no longer global, and instead just and only "returned".

ct at filanet dot dk
24-Oct-2002 11:32

It is not correct that '�' is ASCII 228. In fact, ASCII only defines characters in the range 0-127.

But '�' is character 228 in the ISO 8859-1 (also known as Latin-1) character set.

peka yashuu de
21-Nov-2002 08:56

`that $var becomes no longer global, and instead just and only "returned".`

The reason for this would be, that you return the value of the variable, not the variable itself and a value can`t be global, can it?

someone at somewhere dot com
23-Dec-2002 06: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...

gabriel at bumpt dot net
13-Jan-2003 04: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.

unleaded at nospam dot unleadedonline dot net
15-Jan-2003 01: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

phValue at example dot com
04-Mar-2003 01: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!

Tom Andrews at cfl dot rr dot com
03-Apr-2003 08:02

charecter 228 (�) is not in the ascii 0-127 but is in extended ascii, which is 128-255
pekka at SPAMphotography-on-theSPAM dot net
29-Apr-2003 07: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 "
<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);

daevid at daevid dot com
01-May-2003 12:47

While this may or may not be obvious, to use references with a function, do it like this...

function timeStampNotes($notes)
{
if ($notes != "")
$notes = "\n\n[".date("m/d/Y h:iA")."]"\n".$notes;
}

timeStampNotes(&$contact_notes);

notice that you use the & in the passing, not in the function itself...

If your notes are getting to be large textareas (like with a database), this may be faster than sending it the normal way.

damonhastings at yahoo dot com
20-May-2003 11:44

I might mention that stlawson's comment is directly contradicted in Chapter 15: . 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: . (Actually, Daevid's syntax is still legal, but they're phasing it out.)

add a note add a note

<Type JugglingPredefined variables>
 Last updated: Tue, 22 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Sat May 24 21:09:36 2003 CEST