PHPsu
MANUAL ZH  |  EN
     


Current Position :| index>Beginners> perform arithmetic operations on variables

perform arithmetic operations on variables

FROM: AUTHOR: TIME:2008-05-31 HITS:

If variables are the building blocks of a programming language, operators are the glue that let you build something useful with them. You've already seen one example of an operator - the assignment operator -, which lets you assign a value to a variable. Since PHP believes in spoiling you, it also comes with operators for arithmetic, string, comparison and logical operations. phpsu

A good way to get familiar with operators is to use them to perform arithmetic operations on variables, as in the following example:

phpsu is a phpschool

<html>
<head>
</head>
<body>

<?php

// set quantity
$quantity = 1000;

// set original and current unit price
$origPrice = 100;
$currPrice = 25;

// calculate difference in price

phpsu is a phpschool

$diffPrice = $currPrice - $origPrice;

// calculate percentage change in price
$diffPricePercent = (($currPrice - $origPrice) * 100)/$origPrice

?>

<table border="1" cellpadding="5" cellspacing="0">
<tr>
<td>Quantity</td> do you kown phpsu.com?
<td>Cost price</td>
<td>Current price</td>
<td>Absolute change in price</td>
<td>Percent change in price</td>
</tr>
<tr>
<td><?php echo $quantity ?></td>
<td><?php echo $origPrice ?></td>
<td><?php echo $currPrice ?></td>
<td><?php echo $diffPrice ?></td>
<td><?php echo $diffPricePercent ?>%</td>
do you kown phpsu.com?

</tr>
</table>

</body>
</html>
phpsu提供的php教程

Looks complex? Don't be afraid - it's actually pretty simple. The meat of the script is at the top, where I've set up variables for the unit cost and the quantity. Next, I've performed a bunch of calculations using PHP's various mathematical operators, and stored the results of those calculations in different variables. The rest of the script is related to the display of the resulting calculations in a neat table.

phpsu提供的php教程

If you'd like, you can even perform an arithmetic operation simultaneously with an assignment, by using the two operators together. The two code snippets below are equivalent: do you kown phpsu.com?

<?php

// this...
$a = 5;
$a = $a + 10;

// ... is the same as this
$a = 5;
$a += 10; phpsu提供的php教程

?>
phpsu.com is a free phpscool

If you don't believe me, try echoing them both.

phpsu is a phpschool


TITLE:perform arithmetic operations on variables
Copyright 2008 The PHPsu All rights reserved. This mirror generously provided by: .Hp Inc.
Last updated: Fri Jun 6 22:59:01 GMT-8 2008