Skip to main content
  1. Tech
  2. Gadgets & Tech
  3. Tech Gear

Using functions in a PHP program (part 5)

See also

In this article we will discuss and demonstrate passing values to a function in a PHP program. A variable must be anticipated by a function, it cannot just appear. When you pass values to a function, values are placed inside parentheses as shown:

functionname (value, value,..);

The function statement shown below includes the variable names for the values expected:

function functionname ($varname1, $varname2..);

{

statements

return;

}

The PHP programming code listed below demonstrates passing values to a function. For this example, we will use a function to compute the sales tax. As discussed previously in Using a variable in a PHP program, the same rules apply. Please refer to the article for a refresher.

Please Note:

I have installed and used a newer version of the Wampserver package for this program. The newer version is Wampserver (64 bits & PHP 5.5) 2.5, which includes the newer releases of .. Apache : 2.4.9 MySQL : 5.6.17 PHP : 5.5.12 PHPMyAdmin : 4.1.14 SqlBuddy : 1.3.3 XDebug : 2.2.5

Please refer to the following articles for the download, install, configuration and fixing the security hole.

Download, install and configure the web development environment (part 1)

Download, install and configure the web development environment (part 2)

Download, install and configure the web development environment (part 3)

Fixing the security hole that corresponds to the MySql privileged accounts

NOTE: As demonstrated in the previous programs, we used notepad a plain text editor. The PHP programs are stored on our web server, "C:\Wampserver\www." Please note the stored web server location.

Now let us create the PHP program, please follow the steps outlined below:

  1. Select and click "Start."
  2. Select and click "All Programs."
  3. Select and click "Accessories."
  4. Select and click "Notepad."
  5. Type the PHP code exactly as shown below.

<html>

<head>

<title>Sales Tax Calculation</title>

</head>

<body><h1>Sales Tax Calculation</h1>

<h3>Demonstrates use of passing variables to functions<h3>

<?php

$amount = 2000.00;

$clientState = "Virginia";

compute_salestax($amount, $clientState);

function compute_salestax($amount, $clientState)

{

switch ( $clientState )

{

case "Maryland":

$salestaxrate = 0;

break;

case "Virginia":

$salestaxrate = 1.0;

break;

default:

$salestaxrate = .5;

break;

}

$salestax = $amount * $salestaxrate;

print "$$salestax sales tax for the State of $clientState.<p />";

}

?>

</body>

</html>

  1. Once you have type the entire program, Select "File," "Save As," and then go to the webroot of your server. For example, C:\Wampserver\www. Type Filename, calcsalestx.php," and then Select "Save."

In the next article of the Using functions in a PHP program (part 6); we will continue with Passing the right type of values.

Advertisement