Basic Code: Variables

  1. Functions
  2. Basic Code
  3. Custom functions

Rather than immediately echoing the results of functions, you can store them in containers for later use. These containers are called “variables” by programmers. If, for example, you were going to mention the time more than once on your web page, you might want to store the time in a variable and simply echo that variable everywhere on your page. Change the body of your web page to:

<h1>PHP Time</h1>

<?php

$now = date('h:i A');

?>

<p><em>Right now</em> is <?php echo $now; ?>. <?php echo $now; ?> is an important time, because <?php echo $now; ?> is the exact time you visited our wonderful page.</p>

That’s more than a little silly, but you can imagine having the date and/or time showing up in the top of your page, in the footer of your page, and somewhere in the content of your page. And other variables are even more commonly re-used; a person’s name, for example, or a price.

The two main advantages of using variables is that it reduces errors and it makes it easier to changes things later. You only type the date function with its somewhat obscure formatting codes once. And if you change your mind about the format later, you can change it in one place instead of everywhere on the page.

All variables in PHP begin with the dollar sign. In this example, we put the time in a variable called ‘$now’. Suppose later you want to change the time format to 24-hour time. You can change the format to ‘H:i’ on the line “$now = date('h:i A');” and it will change to showing the 24-hour time without the AM/PM in all three places.

  1. Functions
  2. Basic Code
  3. Custom functions