Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Variables

Variables in PHP—that is, things that store data—begin with $ followed by a letter or an underscore, then any combination of letters, numbers, and the underscore character. This means you may not start a variable with a number. One notable exception to the general naming scheme for variables are "variable variables," which are covered in the next chapter. A list of valid and invalid variable names is shown in Table 4-1.

Table 4-1. Valid and invalid variable names

$myvar

Correct

$Name

Correct

$_Age

Correct

$_ __AGE_ __

Correct

$91

Incorrect ; starts with a number

$1Name

Incorrect ; starts with a number

$Name91

Correct; numbers are fine at the end and after the first character

$_Name91

Correct

$Name's

Incorrect; no symbols other than "_" are allowed, so apostrophes are bad

Variables are case-sensitive, which means that $Foo is not the same variable as $foo, $FOO, or $fOO.

Assigning variables is as simple as using the assignment operator (=) on a variable, followed by the value you want to assign. Here is a basic script showing assigning and outputting data—note the semicolons used to end each statement:

    <?php
            $name = "Paul";
            print "Your name is $name\n";
            $name2 = $name;
            $age = 20;
            print "Your name is $name2, and your age is $age\n";
            print 'Goodbye, $name!\n';
    ?>

There we set the $name variable to be the string Paul, and PHP lets us print out that variable after Your name is. Therefore, the output of the first print statement is Your name ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page