#native_company# #native_desc#
#native_cta#

The ABC’s of PHP Part 4 – How Variable Am I? Page 2

By PHP Builder Staff
on April 1, 2009

So what are variables good for?
Variables keep your data all in one place, and make changing
various aspects of your script very simple, consider the
following:

<html>

  <head>

    <title><?php print "My First Script"?></title>

  </head>

  <body>

    <h1><?php print "My First Script"?></h1>

  </body>

</html>


As you can see the same segment of PHP has been used twice
with exactly the same data. What if you needed to change
that data? You would need to make at least 2 changes to the
above script. Now imagine if that script was an extra 200
lines long and you had half of those lines with the phrase
“My First Script” in them.
Now lets take the previous example and use a variable in it:

  <?php $phrase "My First Script"?>

  <html>

    <head>

      <title><?php print $phrase?></title>

    </head>

    <body>

      <h1><?php print $phrase?></h1>

    </body>

  </html>


As you can see we’ve added a new line that sets the variable
named $phrase to the value of:

"My First Script"
The variable is then used in place of the previous 2 lines
where it’s referenced simply by using it’s name. If you try
changing the value of the variable, then re-run the script
in your browser you’ll see that the text in the web-page
will change to match.
Variables can also take functions.
If you change the first line of the above script to be:

$phrase = date("r");

You’ll see that your script then displays the current time
and date, just as with the previous parts script where we
fed the output directly to the print statement. The above
example feeds the output of the date to the contents of the
variable, which can then be reused.