Hudzilla.org - the homepage of Paul Hudson
Contents > Introducing PHP Wish List | Report Bug | About Me ]

2.6     How PHP is written

This is NOT the latest copy of this book; click here for the latest version.

As explained already PHP code is embedded inside HTML, making a complete PHP script. By default, PHP operates with PHP mode turned off - all text read in a script is considered to be HTML unless PHP mode has been enabled.

This method of parsing means that the PHP elements of a script are "code islands"; standalone chunks of code that can work independently of the HTML "sea" around them. That is not to say that the PHP code cannot affect the HTML - far from it! We will get there soon.

PHP scripts are generally saved with the file extension .php to signify their type. Whenever your web server is asked to send a file ending with .php, it first passes it to the PHP interpreter, which executes any PHP code in the script before returning a generated file to the end user. Each line of PHP code is called a statement, and ends with a semi-colon to signify it is a complete statement.

Variables in PHP, that is, objects that store data, all 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, so be careful. Here is a list of 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 equals operator (=) on a variable, followed by the value you want to assign. Here is a basic script showing assigning and outputting data - note the semi-colons 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';
?>

As you can see, we set the $name variable to be the string "Paul", and PHP lets us print out that variable alongside "Your name is". Therefore, the output of the first print statement is "Your name is Paul", because PHP will substitute $name for its value whenever it finds it by itself, or inside a double-quoted string (that is, one starting and ending with "").

Author's Note: The technical term for "variable substitution" is "variable interpolation".

We then set $name2 to be $name, which effectively copies $name's information into $name2 entirely. $name2, therefore, is now also set to "Paul". We also set up the $age variable to be the integer 20. Our second print statement outputs both variables at once, as again PHP will substitute them inside the string.

The last print statement will not do what was expected, however. It will print:

Goodbye, $name!\n

The reason for this is that PHP will not perform variable substitution for variables inside single-quoted strings, and won't even replace the escape characters. Whereas in double-quoted strings, PHP will replace the variable $name with its value, in a single-quoted string, PHP will consider $name to mean that you actually want it to output the word "$name" just like that.

There is a tiny (tiny) performance gain available using single quotes in place of double quotes, because PHP does not have to bother scanning for variables.

One final note before we go onto other topics. Occasionally you may run into the situation where you want to tack a value onto your variable inside your strings, but you find that PHP considers these characters to be part of the variable. Take a look at this code:

<?php
    $food
= "grapefruit";
    print
"These $foods aren't ripe yet.";
?>

Ideally what we wanted to be printed was "These grapefruits aren't ripe yet", but because we have added the S to the end of the variable name, we have changed it from trying to read $food to trying to read $foods. The variable $foods does not exist, so PHP will leave the space blank. How to solve this? Well, we need to make it clear to PHP where the variable starts and ends, and there are two ways to do this:

<?php
    $food
= "grapefruit";
    print
"These ${food}s aren't ripe yet.";
    print
"These {$food}s aren't ripe yet.";
?>

Both of those are valid and should work as expected. The braces, { and }, tell PHP where the variable ends. Note that code like this will work without modification:

<?php
    $food
= "grapefruit";
    print
"This $food's flavour is bad.";
?>

That will work fine because you are not allowed to use an apostrophe as part of your variable names. If you want to make your life easy you can just avoid the problem entirely by not getting PHP to substitute the variable:

<?php
    $food
= "grapefruit";
    print
"These " . $food . "s aren't ripe yet.";
?>




<< 2.5 Running PHP scripts   2.6.1 Whitespace >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 07 Sep 2008

superb till now I'm enjoying it!!!!!!!!!

Dr Dre - 07 Sep 2008

I have MAMP installed but when I tpe in the following into TextEdit in Mac

<html>
<head></head>
<body>

Hi

<br/>

<?php
echo 'Hallo';
?>

</body>
</html>


and save it as "index.php", then open it up in Mozilla, it only shows "hi". What could be the problem??

Blank for PHP code other than PHP info - 07 Sep 2008

it is sure that you are making some syntax mistake.
type out your code here. somebody will point out the mistake

happened with me too while learning it

valsj - 07 Sep 2008

this site is very nice for a beginer like me.

Kaolin Fire - 07 Sep 2008

\n is not a linefeed in the "browser", so that's not strange at all. You may be looking for &lt;br /&gt;, but really you should look at all the markup available to you, including css, for what you need as a "linefeed".

amol_bhavsar1982@yahoo.co.in - 07 Sep 2008

Hi,this is a great site for those programmers who are new to php,Thanks to author & publisher as well,bye.

A PHP User - 07 Sep 2008

So confused.

When I run this script, it shows that I have php on the server.

<?php
phpinfo();
?>

However, none of the other scripts are working. They all come up with a blank page?

Any suggestions?

Thank you.

doctorhore - 07 Sep 2008

to seperate adjacent lines by a single line in the browser simply use the following code:

print "<br/>"; eg

<html>
<head><title>myphp.org</title></head>
<body bgcolor = green text=blue>
<marquee
behaviour=alternate direction=left <font >
<h1>HORE AKATOZVIPENGERWA ZVAKE</h1></font>
</marquee>
<br>
<font color=red><p> yes baba</font>
<br>
<br>
<?php
$name = "Doctor";
print "Your name is $name<br/>";
print "<br/>";

$name2 = $name;
$age = 20;

print "Your name is $name2, and your age is

$age<br/>";
print "<br/>";

print "Goodbye, $name!<br/>";
print "<br/>";
?>
</body>
</html>

doctorhore - 07 Sep 2008

<?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';
?>

I am made to understand from what I read from your book that the \n means newlines. Just the enter buttom, so the next text will start at a new line.
Can you put that in it?

A PHP User - 07 Sep 2008

<?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';
?>

The \n means newlines. Just the enter buttom, so the next text will start at a new line.
Can you put that in it?

--------------------------------------------------------------------------------
So confused.

When I run this script, it shows that I have php on the server.

<?php
phpinfo();
?>

However, none of the other scripts are working. They all come up with a blank page?

Any suggestions?

Thank you.

---------------------------------------------------------------------------------

Are you really sure that you got php? If you got blank pages, i'm quiet sure that you don't got php at your server.

A PHP User - 07 Sep 2008

<?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';
?>

The \n means newlines. Just the enter buttom, so the next text will start at a new line.
Can you put that in it?

--------------------------------------------------------------------------------
So confused.

When I run this script, it shows that I have php on the server.

<?php
phpinfo();
?>

However, none of the other scripts are working. They all come up with a blank page?

Any suggestions?

Thank you.

---------------------------------------------------------------------------------

Are you really sure that you got php? If you got blank pages, i'm quiet sure that you don't got php at your server.

Suresh Krishna SEO - 07 Sep 2008

Hello, I'm an Beginner,
Ohh, this' site's great!
My friend has suggested this book, it's very easy and i like it so much..., my favourite program's language are Php and Perl..., Thanks for this book, it's very useful..

Suresh Krishna
India

A PHP User - 07 Sep 2008

I think \n works in browsers, but you'll have to view source to see the effect ;)

A PHP User - 07 Sep 2008

also instead of <br/> i used <br> to make new lines
(php v5)

A PHP User - 07 Sep 2008

So confused.

When I run this script, it shows that I have php on the server.

<?php
phpinfo();
?>

However, none of the other scripts are working. They all come up with a blank page?

Any suggestions?

Thank you.

A PHP User - 07 Sep 2008

So confused.

When I run this script, it shows that I have php on the server.

<?php
phpinfo();
?>

However, none of the other scripts are working. They all come up with a blank page?

Any suggestions?

Thank you.

A PHP User - 07 Sep 2008

So confused.

When I run this script, it shows that I have php on the server.

<?php
phpinfo();
?>

However, none of the other scripts are working. They all come up with a blank page?

Any suggestions?

Thank you.

A PHP User - 07 Sep 2008

So confused.

When I run this script, it shows that I have php on the server.

<?php
phpinfo();
?>

However, none of the other scripts are working. They all come up with a blank page?

Any suggestions?

Thank you.

A PHP User - 07 Sep 2008

So confused.

When I run this script, it shows that I have php on the server.

<?php
phpinfo();
?>

However, none of the other scripts are working. They all come up with a blank page?

Any suggestions?

Thank you.

cmani@yahoo.com - 07 Sep 2008

Ques : The Line feed character \n does not work ?
Ans : It may not work on a non-unix OS.

Type the following code and view it in your browser, with WAMP environment (Windows, Apache, MySql, PHP)

<?php
$name = "Paul";
print "Your name is $name \n";
print "Thank you\n";
?>

view it in the browser, it will give the output as

Your name is Paul Thank you

without line feed.. Now try the following code

<?php
$name = "Paul";
print "Your name is $name <br />";
print "Thank you <br />";
?>

view it in the browser, it will give the output as

Your name is Paul
Thank you

The previous poster - 07 Sep 2008

I just checked out escaping curly braces, and I noted, that them should not be escaped if there's no variable inside them. If there's a variable inside them, you should only escape the first (opening) brace, and not the closing one.

A PHP User - 07 Sep 2008

gerymate: If you want to print out characters, which have a special meaning (like "{", "}" and "\"), you must escape them. This means you have to put a "\"-sign in front of the letter to be escaped. Example: You want to ouput {hello}. The correct way to do this is to put a "\"-sign in front of the special characters, like this \{hello\}.

gerymate - 07 Sep 2008

How to output curly braces, eg. '{' and '}' in double quoted strings? What if I want '{grapefruit}' to be the exact output?

The Frankman - 07 Sep 2008

I'm learning UNIX and are using PHP to store data for my form (Basic Stuff). However, my instructor isn't allowing me to use C++ to store the form data, opting for PHP. How would I make it do addition/subtraction/etc.? I'm new to the language.

A PHP User - 07 Sep 2008

another view:
if i type beforehand "php", like:
php
<?php
phpinfo();
?>
then it does nothing - like waiting some closing mark?

AT

A PHP User - 07 Sep 2008

another view:
if i type beforehand "php", like:
php
<?php
phpinfo();
?>
then it does nothing - like waiting some closing mark?

AT

A PHP User - 07 Sep 2008

hi!

I'm trying use php in IIS5.1 on windows XP sp2 computer...
the problem with my command line is (start>run>cmd > cd to where localhost is located), that it doesn't allow me to produce more than one line and if I make "Return" then it tries to execute it and ofcourse with no success.
But if I save the code in a php-file then it executes it almost Ok; (ofcourse no different rows and all >tag>s inside.
So i can't type in command line any syntax!

Of course - i'm very beginner...
AT

A PHP User - 07 Sep 2008

hi!

I'm trying use php in IIS5.1 on windows XP sp2 computer...
the problem with my command line is (start>run>cmd > cd to where localhost is located), that it doesn't allow me to produce more than one line and if I make "Return" then it tries to execute it and ofcourse with no success.
But if I save the code in a php-file then it executes it almost Ok; (ofcourse no different rows and all >tag>s inside.
So i can't type in command line any syntax!

Of course - i'm very beginner...
AT

mitch - 07 Sep 2008

this site reads very nice on my psp, thanks

Adam - 07 Sep 2008

Great Job Man!... I have a feeling that this book is going to make me rich as a freelancer thank you so much... my gift to you is the satisfaction of someone else learning the art of PHP programming

Daniela - 07 Sep 2008

Hello, I'm an itlian girl...
Ohh, this' site's great!
I'm studying for programmer, it's so hard but i like it so much..., my favourite program's language are Php and Perl..., Thanks for this book, it's very useful..

Ciao Ciao...
Daniela

A PHP User - 07 Sep 2008

Nice to see some prog rock band sugestions. That was actually what i was looking for, before I accidently browsed into this world of php. I will check out "At The Drive In" before I go to bed, reading the "book", this far.

evoman142 - 07 Sep 2008

haeberle@videotron.ca wrote:
"I am coding in Dreamweaver and the statement:

print "Your name is $name\n";

does not produce a LF in the browser.

strange?"

No, not strange at all. For a browser to produce a line feed use the the <br> html statement instead. \n will only work at teh command line.

A PHP User - 07 Sep 2008

Is there a PHP script that will prevent people < 14 years old from submitting comments? Seriously though, great job on the book and all. I came upon this site from some web browsing, and decided to sit down and read it, because I was coincidentally offered a PHP distro by a friend not 1 hour ago. This also worked out beautifully, because I just installed Ubuntu Linux, which comes with Python, and I was planning on learning that, but because of how well written this book is, I plan on learning PHP instead. Very good job, keep up the good work!

PS: I am a college student in Denver, CO, and cannot afford to donate anything monetarily, but I could point you in the direction of some good music. Check out The Mars Volta for some excellent progressive rock (think Pink Floyd), as well as Beck's new album, Guero. At The Drive In is another great prog rock band, but they are essentially 1/2 of The Mars Volta, pre break-up. Sorry for the long-winded post, keep up the great work, I can't wait for it to get published!

haeberle@videotron.ca - 07 Sep 2008

I am coding in Dreamweaver and the statement:

print "Your name is $name\n";

does not produce a LF in the browser.

strange?

haeberle@videotron.ca - 07 Sep 2008

I am coding in Dreamweaver and the statement:

print "Your name is $name\n";

does not produce a LF in the browser.

strange?

A PHP User - 07 Sep 2008

asfdasfsafasfdsafdsaff
dasfdasf
asdfdsafa
fdasfds
fdasf

saudi guy - 07 Sep 2008

i think we can use double-quoted with a single quoted
like this:

echo "hi".' how are you '."fine?";

Tochjo - 07 Sep 2008

The last example with single quotes would be

<?php
$food = "grapefruit";
print 'These ' . $food . 's aren\'t ripe yet.';
?>

The backslash is required. If it wasn't there you'd get an error because then the string would supposedly end after "aren". By putting the backslash there it sees the apostrophe in "aren't" as text.

A PHP User - 07 Sep 2008

Yes, but he would have to concatenate out aswell

<?php
$food = "grapefruit";
print 'These ' . $food . 's aren't ripe yet.';
?>

Keith - 07 Sep 2008

Okay, so single quots mean no substitution. That said, then the last example of your code could have been done using single quotes for that tiny (tiny) performance gain, right?



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is four plus nine?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow