One of the central canons of programming is DRY: Don’t Repeat Yourself. If you are using a programming routine more than once, it should usually be written as a function.

Functions are procedures that, in their basic mode of operation, have little variation in their execution: they go through a set order of tasks that do not change much. For example, you might have a set list of things that you do each morning of the working week:

  1. Turn off alarm.
  2. Get up.
  3. Have shower.
  4. Dress.
  5. Make breakfast.

When those tasks take place may change: some days your alarm may go off at 6.30am, other days you may wake up at 8am. Certain tasks might take longer than usual on some days. But the order rarely changes.

If you had the world’s most mundane blog, and wanted to tell the world about every activity in your morning routine, you could write down this sequence every day, or you could turn it into a function.

Functions are removed from the normal order of execution of PHP: functions are ignored until they are called upon to act. Because of that, they can be written anywhere in a document… but because they must be written before they are called, they are usually written near the top of the page. A function that produced a list of morning activities could look something like this:

<?php function morningRoutine() { 
	echo "<h3>".date('jS \o\f F, Y')."</h3>";
	echo "<p>Turned off alarm. Got up. Had a shower. Dressed. Made breakfast.</p>";
} ?>

The function would be called lower down on the page with:

<?php morningRoutine(); ?>

Now the world’s most boring blog entries could be generated by you calling the morningRoutine function every day. For a tad more excitement, you might want to add the time you woke up. The function itself can’t know this, so you would have to pass this information to it:

<?php $morningRoutine(“6am”); ?>

When the function receives the information, it must handle it as a variable, and then use it in some way:

<?php function morningRoutine($wakeUpTime) {
	echo "<h3>".date('jS \o\f F, Y')."</h3>";
	echo “<p>Turned off alarm at ".$wakeUpTime.".
	Got up. Had a shower. Dressed. Made breakfast.</p>";
} ?>

This will produce the following:

12th of November, 2010

Turned off alarm at 6am. Got up. Had a shower. Dressed. Made breakfast.

This is, of course, a very simple example: functions can do a great deal more, including returning values.

Enjoy this piece? I invite you to follow me at to learn more.