PHP Variables

Taking our first lesson; Hello World Example, we are going to spice it up a bit and use variables with our PHP file. Let’s start right away by looking at an example then explaining what we did.

<html>
<head>
<title>PHP Tutorial</title>
</head>
<body>
<?php
$var = "PHP is cool";
echo "<p>$var</p>";
?>
</body>
</html>

As you can see the line we really care about is

$var = "PHP is cool";
echo "<p>$var</p>";

This says define a variable called $var and give it the data of “PHP is cool”; , then we simply display the data using the echo command.

Using Constants
You saw above how to create variables and display the data, now we are going to take a look at creating ‘constant ‘ variables. Constant variables typically do not change. They work well at the top of document if you know that you need to define something that will not change, let’s take a look at a sample:

define("SALES_TAX",.05);

This creates a constant with the name name and the value is Tom Fitzgerald. You’ll notice that constants do not require the $ before the variable name, and variables are traditionally defined in all upper case. This is not required but it can be easier when reading your code so you know what is a constant and what is not easily. You can now view the value by doing…

echo SALES_TAX


Simple Calculations

Now let’s do some simple calculations using our variables and constant.

define("SALES_TAX",.05);
$Amount_Purchased = 5.45;
$Tax_Amount = $Amount_Purchased * SALES_TAX;

This takes our constant SALES_TAX and our variable Amount_Purchased and multiplies the two to get the tax amount.

Note: Make sure if you are doing a calculation you are defining the variable correctly, for example:

This is the correct way $Amount = 3
This is incorrect $Amount = “3” ;

Quotes are used only when defining a text variable or something you don’t want to ever run a calculation on.

This is pretty simple so far so lets just view some more simple calculations:

$var1 = 3;
$var2 = 5;
$total = $var1 + $var2;
$total = $var1 * $var2;
$total = $var1 / $var2

This shows how we can do easy addition, multiplication and division using our new variables, good job.