#native_company# #native_desc#
#native_cta#

The ABC’s of PHP Part 3 – Basic Script Building in PHP

By Peter Shaw
on March 26, 2009

Welcome to part 3 of my 10 part series on PHP. In the first
two parts I introduced you to the language and to what
software you needed to run it.
In this episode we will look at some simple PHP syntax, and
we’ll write a couple of small scripts to get our feet wet,
and get a feel for the language.
What does a PHP script look like?
PHP traditionally is embedded into HTML code within a web
page, as this was its initial intent. However it’s becoming
increasingly more popular for web application authors to
write and generate the HTML using PHP from a page that is
made entirely of PHP code.
The following two examples of the world renowned hello world
program should help to show the difference:
Embedding in HTML
<html>
  <head>
    <title><?php print "My First Script"; ?></title>
  </head>
  <body>
    <?php
        
        print "<h1>Hello World</h1>";

      ?>
    </body>
  </html>
Full PHP

  <?php

    $content "<html>nt<head>ntt<title>";

    
$content .= "My First Script";

    
$content .= "</title>nt</head>n";

    
$content .= "t<body>nt<h1>";

    
$content .= "Hello World";

    
$content .= "</h1>n</body>n</html>";

    print $content;

  ?>




Edited for correctness

When run using your web server set up, both scripts will
produce the following:

  <html>
    <head>
      <title>My First Script</title>
    </head>
    <body>
      <h1>Hello World</h1>
    </body>
  </html>

My personal preference is embedding the PHP code within the
HTML code, however there are plenty of alternative theories
out there, and I would encourage you to explore and develop
your own style of writing scripts.
As an example if you ever decide to work with the Typo3
framework (http://www.typo3.org/) then you’ll be highly
likely to use the Full PHP approach. For the remainder of
this series we’ll be using the embedded HTML approach.
The first script line by line
As you can see most PHP statements are included in special
PHP tags which for the most part are no different to regular
HTML tags.
Because of this, we can freely use them inter-changeably
anywhere you would use any other HTML tags.
Looking at the title line in the first example above, you
can see that we generate the title using PHP code and a
static string. You could use a variable, but since we’re
not covering them until next time I’ll skip over that for
now.