Richland College Multimedia Learning Center

Digital Media Programming with PHP and MySQL
Updated 3/2/2020 at 5:50pm

PHP Functions and Variable Scope

In this handout you will learn how to use and create functions in PHP.


Handling Checkboxes

HTML forms often contain checkboxes. Checkboxes require a bit of special processing in the PHP code that receives the form data.

The Checkbox Demo has an HTML page with a form in it, and a separate PHP action page that processes the form data.

The code for the Checkbox Demo is shown below. The first page is checkDemoForm.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="myStyles.css">
  <title>Checkbox Demo</title>
</head>
<body>
  <div id="mainDiv">
    <h1>Checkbox Demo</h1>
    
    <h3>Demonstrates checkboxes</h3>
    
    <form action = "checkDemoAction.php" method="post">
    
    <h3>What would you like with your order?</h3>
    <ul>
      <li><input type = "checkbox"
                 name = "chkFries"
                 value = "1.00">Fries
      </li>
      <li><input type = "checkbox"
                 name = "chkSoda"
                 value = ".85">Soda
      </li>
      <li><input type = "checkbox"
                 name = "chkShake"
                 value = "1.30">Shake
      </li>
      <li><input type = "checkbox"
                 name = "chkKetchup"
                 value = ".05">Ketchup
      </li>
    </ul>
    
    <input type = "submit" value="Place your order">
    </form>
  </div>
</body>
</html>

The second page is checkDemoAction.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="myStyles.css">
  <title>Checkbox Demo</title>
</head>
<body>
  <div id="mainDiv">
    <h1>Checkbox Demo</h1>
    
    <h3>Demonstrates reading checkboxes</h3>
    
    <?php
    
    if (isset($_POST["chkFries"]))
    {
      $item1Cost = $_POST["chkFries"];
    }
    else
    {
      $item1Cost = "";
    }
    
    if (isset($_POST["chkSoda"]))
    {
      $item2Cost = $_POST["chkSoda"];
    }
    else
    {
      $item2Cost = "";
    }
    
    if (isset($_POST["chkShake"]))
    {
      $item3Cost = $_POST["chkShake"];
    }
    else
    {
      $item3Cost = "";
    }
    
    if (isset($_POST["chkKetchup"]))
    {
      $item4Cost = $_POST["chkKetchup"];
    }
    else
    {
      $item4Cost = "";
    }
    
    $total = 0;
    
    if ($item1Cost != "")
    {
      print ("You chose Fries<br>");
      $total = $total + $item1Cost;
    }
    
    if ($item2Cost != "")
    {
      print ("You chose Soda<br>");
      $total = $total + $item2Cost;
    }
    
    if ($item3Cost != "")
    {
      print ("You chose a Shake<br>");
      $total = $total + $item3Cost;
    }
    
    if ($item4Cost != "")
    {
      print ("You chose Ketchup<br>");
      $total = $total + $item4Cost;
    }
    
    print ("<br>The total cost is \$$total");
    ?>
  </div>
</body>
</html>

Please note these points about the above Checkbox Demo code:


The printf( ) Function

You may have noticed that the "total" number in the previous section's sample page does not always look very pretty. For instance,

The total cost is $0.9
does not look normal. We are used to seeing
The total cost is $0.90

PHP has a built-in function, printf( ), which allows you to control the formatting and display of numbers such as the dollar totals in the sample above.

The syntax of printf( ) is like this:

  printf (<format> [,argument [,argument [,...]]]);

where <format> is a string which can contain normal text and some special formatting characters, or just formatting characters; and [,argument [,... is/are the item(s) that you want to format.

For example, in the sample code above, we could put this line of code in place of the current "total" line:

  printf("<br />The total cost is \$%01.2f", $total);

Please note these points about the format string above:

A more detailed description of the available format characters is at http://www.php.net/manual/en/function.sprintf.php which is specifically in the section for sprintf( ), but printf( ) uses the same formatting characters. Make sure you scroll down to the many examples, also.


Creating Custom Functions

When your PHP code pages get longer and more involved, you will probably need to break up the code into manageable chunks. One way to do this breaking up is to make your own functions.

The This Old Man Page shows how to make and use your own functions.

And as a reminder, a function is a named group of code which does something. A function often returns a value to the place in your code where the function is called/run from.

The code for the This Old Man Page is shown below. This is page thisOldMan.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="myStyles.css">
  <title>This Old Man</title>
</head>
<body>
  <div id="mainDiv">
    <h1>This Old Man</h1>
    <h3>Demonstrates use of functions</h3>
    <?php
    
    verse1();
    chorus();
    verse2();
    chorus();
    
    function verse1(){
      print <<<HERE
      This old man, he played 1<br />
      He played knick-knack on my thumb<br /><br />
HERE;
    } // end verse1
    
    function verse2(){
      print <<<HERE
      This old man, he played 2<br />
      He played knick-knack on my shoe<br /><br />
HERE;
    } // end verse1
    
    function chorus(){
      print <<<HERE
      ...with a knick-knack<br />
      paddy-whack<br />
      give a dog a bone<br />
      this old man came rolling home<br />
      <br /><br />
HERE;
    } // end chorus
    ?>
  </div>
</body>
</html>

Please note these points about the above This Old Man Page's code:


Functions with Parameters

Functions are meant to be self-contained. If your function needs any information from elsewhere in the page, the best way to provide the data and information that your function needs is to use parameters.

Please note these points about using parameters:

The Param Old Man Page shows how to use parameters and a return in your functions.

The code for the Param Old Man Page is shown below. This is page param.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="myStyles.css">
  <title>Param Old Man</title>
</head>
<body>
  <div id="mainDiv">
    <h1>Param Old Man </h1>
    <h3>Demonstrates use of function parameters</h3>
    <?php
    
    print verse(1);
    print chorus();
    print verse(2);
    print chorus();
    print verse(3);
    print chorus();
    print verse(4);
    print chorus();
    
    function verse($stanza){
      switch ($stanza){
        case 1:
          $place = "thumb";
          break;
        case 2:
          $place = "shoe";
          break;
        case 3:
          $place = "knee";
          break;
        case 4:
          $place = "door";
          break;
        default:
          $place = "I don't know where";
      } // end switch
    
      $output = <<<HERE
      This old man, he played $stanza<br>
      He played knick-knack on my $place<br><br>
HERE;
      return $output;
    } // end verse
    
    function chorus(){
      $output = <<<HERE
      ...with a knick-knack<br>
      paddy-whack<br>
      give a dog a bone<br>
      this old man came rolling home<br>
      <br><br>
HERE;
      return $output;
    } // end chorus
    
    ?>
  </div>
</body>
</html>

Please note these points about the above Param Old Man Page's code:


A Second Parameter Example

Here is a second example of how to use parameters in a custom function. Recall that by "custom function", I mean one that you define (write) in your PHP page.

In this second example I will show how to use these features of PHP:

  1. Multiple parameters
  2. String values as parameters
  3. Boolean values as parameters

You can see the second example pages running here.

The HTML form page is SecondExample.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="myStyles.css">
  <title>Custom Function Demo</title>
</head>
<body>
  <div id="mainDiv">
    <h1>Custom Function Demo</h1>
    
    <form action = "SecondExample.php" method="post">
    
    <h3>Please choose your favorite color</h3>
    <ul>
      <li><input type = "radio"
                 name = "favColor"
                 value = "red"> red
      </li>
      <li><input type = "radio"
                 name = "favColor"
                 value = "orange"> orange
      </li>
      <li><input type = "radio"
                 name = "favColor"
                 value = "yellow"> yellow
      </li>
      <li><input type = "radio"
                 name = "favColor"
                 value = "green"> green
      </li>
      <li><input type = "radio"
                 name = "favColor"
                 value = "blue"> blue
      </li>
      <li><input type = "radio"
                 name = "favColor"
                 value = "indigo"> indigo
      </li>
      <li><input type = "radio"
                 name = "favColor"
                 value = "violet"> violet
      </li>
    </ul>
    
    <input type = "submit" value="Next >>">
    </form>
  </div>
</body>
</html>

The form's action page is SecondExample.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="myStyles.css">
  <title>Custom Function Demo</title>
</head>
<body>
  <div id="mainDiv">
    <h1>Custom Function Demo</h1>
    
    <?php
    
    function displayColorInfo($itemInfo, $addColorBox)
    {
      if (isset($_POST[$itemInfo]))
      {
        $colorValue = $_POST[$itemInfo];
      }
      else
      {
        $colorValue = "Not picked";
      }
      
      if ($colorValue != "Not picked")
      {
        print "You chose ";
        print $colorValue;
        print "<br>";
        
        if ($addColorBox)
        {
          print "<div style='width:40px; height:40px; background-color:$colorValue;'> </div>";
        }
      }
      else
      {
        print "It would be nice if you would pick a color!  Please go back!";
      }
    }
    
    print "<h3>This section will NOT show the color box</h3>";
    displayColorInfo("favColor", False);
    
    print "<br><br>";
    
    print "<h3>This section will show the color box</h3>";
    displayColorInfo("favColor", True);
    
    ?>
  </div>
</body>
</html>

Please note these points about the above code:


Variable Scope

A variable that is created outside a function is a global variable. This term means that the variable can be used anywhere in the page.

But if you need to use a global variable inside a function, you must explicitly tell PHP that the variable is global. If you do not, PHP will treat the variable as a variable that is local only to that function. This feature is designed into PHP. It is not a bug. Seriously.

The Scope Demo Page shows how to use a global variable inside a custom function.

The code for the Scope Demo Page is shown below. This is page scope.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="myStyles.css">
  <title>Scope Demo</title>
</head>
<body>
  <div id="mainDiv">
    <h1>Scope Demo</h1>
    <h3>Demonstrates variable scope</h3>
    
    <?php
    
    $a = "I have a value";
    $b = "I have a value";
    
    print <<<HERE
      outside the function, <br>
      \$a is "$a", and<br>
      \$b is "$b"<br><br>
HERE;
    
    myFunction();
    
    function myFunction(){
    
      //make $a global, but not $b
      global $a;
    
      print <<<HERE
        inside the function, <br>
        \$a is "$a", and<br>
        \$b is "$b"<br><br>
HERE;
    } // end myFunction
    
    ?>
  </div>
</body>
</html>

Please note these points about the above Scope Demo Page's code:


A Better Way

Even though you can use global variables in a function, as shown in the previous section, many philosophers of programming say that it is better practice to send the global information into the function via parameters. The following revision of the previous sample code shows how this use of parameters might look.

This is page globalDemo.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="myStyles.css">
  <title>Scope Demo</title>
</head>
<body>
  <div id="mainDiv">
    <h1>Scope Demo</h1>
    <h3>Demonstrates variable scope</h3>
    
    <?php
    
    $a = "I have a value";
    $b = "I have another value";
    
    print <<<HERE
      outside the function, <br>
      \$a is "$a", and<br>
      \$b is "$b"<br><br>
HERE;
    
    function myFunction($aardvark, $elephant){
      $myStuff = <<<HERE
        inside the function, <br>
        \$aardvark is "$aardvark", and<br>
        \$elephant is "$elephant"<br><br>
HERE;
      return $myStuff;
    } // end myFunction
    
    print myFunction($a, $b);
    ?>
  </div>
</body>
</html>

Please note these points about the revised code: