PHP Index

In order to become familiar with PHP programming structures and commands, we will build various PHP pages. Sections of this page will explain each PHP command, provide a link to a working sample, and detail the working sample's PHP code. Let's get started:

Constants

Now that you have been introduced to variables, it is time to learn about 'fixed' variables, or constants. Constants are variables that are assigned a semi-permanent or permanent value. For example, you might want to define a constant variable to hold sales tax percentage. Sales taxes tend to stay the same over an extended period of time, however, sales taxes might go up (or down). A constant allows you to define your fixed variable in one place. If there is a change, you only need to update your constant definition and your code will continue to work.

Define constants using the define function, like so:

define("SALES_TAX", .07859358);

define("TEACHER", "Mr. Chagoyan");

define("PI", 3.1415926535);

It is good practice to use all capitals for your constant names for easy identification.

Here's another example: constants.php


<html>
<head>
<title>constants.php</title>
</head>
<body>
<?php
//Interest Calculation

//Set the variables and constants
define("INTEREST_RATE".19);
$balance1=115000.00;
$balance2=15000.00;
$balance3=177000.00;
$balance4=10000.00;

//Calculate the annual interest amounts for each balance
$annualinterestamount1 $balance1*INTEREST_RATE;
$annualinterestamount2 $balance2*INTEREST_RATE;
$annualinterestamount3 $balance3*INTEREST_RATE;
$annualinterestamount4 $balance4*INTEREST_RATE;

//Display browser output
print("The annual interest due on your first balance of ".$balance1); 
print(
" is "$annualinterestamount1). " dollars.";
print(
"<br><br>");

print(
"The annual interest due on your second balance of ".$balance2); 
print(
" is "$annualinterestamount2). " dollars."
print(
"<br><br>");

print(
"The annual interest due on your third balance1 of ".$balance3); 
print(
" is "$annualinterestamount3). " dollars."
print(
"<br><br>");

print(
"The annual interest due on your fourth balance of ".$balance4); 
print(
" is "$annualinterestamount4). " dollars."
print(
"<br><br>");

 
?>

</body>
</html>