<!doctype html>
<?php
  date_default_timezone_set("America/New_York");
?>
<html lang="en">
  <head>
    <title>How to create and use a library of functions</title>
    <link href="https://jimgerland.com/includes/css/styles.css" rel="stylesheet" />
    <link href="https://jimgerland.com/includes/css/codestyles.css" rel="stylesheet" />
  </head>
  <body>
    <h1>How to create and use a library of functions</h1>
    <h2>A library of functions (the <code>cart.php</code> file)</h2>
    <div style="font-family: Courier, Arial, Sans-Serif; font-size: large;">
      <pre>
      &lt;php
      // Add an item to the cart 
      function cart_add_item(&$cart, $name, $cost, $quantity) {
        $total = $cost * $quantity; 
        $item = array(
          $name, 'cost' => $cost, 'qty' => $quantity, 'total' => $total 
          ); 
        $cart[] = $item; 
      } 
      // Update an item in the cart 
      function cart_update_item(&$cart, $key, $quantity) { 
        if (isset($cart[$key])) { 
          if ($quantity &lt;= 0) { 
            unset($cart[$key]);
          } else { 
            $cart[$key]['qty'] = $quantity; 
            $total = $cart[$key]['cost'] * $cart[$key]['qty']; 
            $cart[$key]['total'] = $total; 
          } 
        } 
      }
      ?&gt;
      </pre>
    </div>
    <h2>Code that uses the library</h2>
    <div style="font-family: Courier, Arial, Sans-Serif; font-size: large;">
      <pre>
      // load the library 
      require_once('cart.php'); 
      // create an array to store the cart 
      $cart = array(); 
      // call methods from the library 
      cart_add_item($cart, 'Flute', 149.95, 1); 
      cart_update_item($cart, 0, 2);  // update the first item (key of 0)
      $subtotal = cart_get_subtotal($cart); 
      // display the result 
      echo("&lt;p&gt;This subtotal is $" .$subtotal . "&lt;/p&gt;\n");
      </pre>
	  <p>I generally name my library of functions either <code>functions.php</code>, <code>dbfunctions.php</code>, and <code>formfunctions.php</code>.</p>
    </div>
    <p><a href="view_files.php">Back</a></p>
  </body>
</html> 