Get latest news and Web Designing tutoria

Thursday, 28 May 2015

Division in Php


To divide one number by another, the / symbol is used in PHP. If you see 20 / 10, it means divide 10 into 20. Try it yourself:
<?php
$first_number = 10;
$second_number = 20;
$sum_total = $second_number / $first_number;
print ($sum_total);
?>
Again, you have to be careful of operator precedence. Try this code:
<?php
$first_number = 10;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number - $second_number / $first_number;
print ($sum_total);
?>
PHP won't work out the sum from left to right! Division is done before subtraction. So this will get done first:
$second_number / $first_number
And NOT this:
$third_number - $second_number
Using parentheses will clear things up. Here's the two versions for you to try:
Version one
$sum_total = $third_number - ($second_number / $first_number);
Version two
$sum_total = ($third_number - $second_number) / $first_number;
The first version will get you an answer of 98, but the second version gets you an answer of 8! So remember this: division and multiplication get done BEFORE subtraction and addition. Use parentheses if you want to force PHP to calculate a different way.

In the next part, we'll take a look at how PHP handles floating point numbers.

Related Posts:

  • Geting Values from Arrays Here's an example for you to try: <?php $seasons = array("Autumn", "Winter", "Spring", "Summer"); print $seasons[0]; ?> The array is the same one we set up before To get at what is inside of an array, just … Read More
  • Sorting PHP Array values There may be times when you want to sort the values inside of an array. For example, suppose your array values are not in alphabetical order. Like this one: $full_name = array(); $full_name["Roger"] = "Wate… Read More
  • PHP Arrays You know what a variable is – just a storage area where you hold numbers and text. The problem is, a variable will hold only one value. You can store a single number in a variable, or a single string. An array is like … Read More
  • How to Set up a PHP Array First you type out what you want your array to be called ($Order_Number, in the array above) and, after an equals sign, you type this: array( ); So setting up an array just involves typing the word array followed by a p… Read More
  • PHP Functions What is a Function? A function is just a segment of code, separate from the rest of your code. You separate it because it's nice and handy, and you want to use it not once but over and over. It's a chunk of code that … Read More

1 comment: