Functions In PHP

The most useful control statement we have seen so far is the IF statement. Most of our pages have had their code organised into the if and else clauses that determine which content is to be displayed. There are lots of occasions where a function or procedure is really useful to a PHP script. Remember that we can put code into separate files and import them into other scripts. This is common practice with key functions. It is not uncommon for a set of includes to contain groups of functions that are heavily used in the scripts that make up a site as a whole.

Functions differ from procedures in that they return values. In PHP, a function does not have to return a value. The term 'function' covers both procedures and functions as we understand the terms from using BASIC.

The following example is a procedure to work out the highest common factor of two numbers.

<?php
function hcf($a, $b)
{
   $one = $a;
   $two = $b;
   while ($one!=$two)
   {
      if ($one>$two)
      {
         $one = $one - $two;
      }
      if ($two>$one)
      {
         $two = $two-$one;
      }
   }
   return $one;
}
$h = hcf(12, 24);
echo "<p>".$h."</p>";
?>

You can make recursive procedures in PHP. You have to take a bit of care though not to overload the stack with recursive calls. Iterative solutions are preferable when you know that server resources are needed for more than one user.