Why We Need Functions

Functions encapsulate code that performs a particular task. By using parameters, we can make the function perform more general tasks.

Example: Permutations

Suppose you want to print all the possible arrangements of three strings. Here's one way to do it.

<?php
   // Rearrage three strings
   $s1 = "alpha";
   $s2 = "beta";
   $s3 = "gamma";
   echo "$s1 $s2 $s3<br />";
   echo "$s1 $s3 $s2<br />";
   echo "$s2 $s1 $s3<br />";
   echo "$s2 $s3 $s1<br />";
   echo "$s3 $s1 $s2<br />";
   echo "$s3 $s2 $s1<br />";
?>

Define a Function

This works fine. But what if we want do this more than once. Should we just rewrite these 9 lines every time we want to do it?

Here's another way. Put this code into a function and call the function when we want to use the code:

<?php
   // Define a function that performs the desired task
   function rearrange() {
       $s1 = "alpha";
       $s2 = "beta";
       $s3 = "gamma";
       echo "$s1 $s2 $s3<br />";
       echo "$s1 $s3 $s2<br />";
       echo "$s2 $s1 $s3<br />";
       echo "$s2 $s3 $s1<br />";
       echo "$s3 $s1 $s2<br />";
       echo "$s3 $s2 $s1<br />";   
   }

   // Now call the function
   rearrange();
   rearrange();
?>

Use Parameters for Generality

That worked nice. But what if we want a function to that will rearrange any three strings. For that we need parameters -- i.e., variables that we can fill in when we call the function.

<?php
   // Define a function that performs the desired task
   // $s1, $s2, $s3 are parameters that will hold the values we want rearranged
   function rearrange2($s1, $s2, $s3) {
       echo "$s1 $s2 $s3<br />";
       echo "$s1 $s3 $s2<br />";
       echo "$s2 $s1 $s3<br />";
       echo "$s2 $s3 $s1<br />";
       echo "$s3 $s1 $s2<br />";
       echo "$s3 $s2 $s1<br />";   
   }
   
   // Now call the function
   rearrange2("alpha","beta", "gamma");
   rearrange2("delta", "epsilon", "phi");
?>

As this example shows, functions with parameters can be defined to perform very general tasks. They can be used anywhere we like in our programs.