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:

  • phpMyAdmin Database Fields You have four Fields in your table from the previous lesson Although they are set out in rows in the images, the rows are actually the Columns you saw earlier – the Fields. Each Field needs a name. So go ahead and type… Read More
  • Check for blank Textboxes with PHP f you remember the script that we wanted to create earlier it was this: Get the text that a user entered in a textbox on a form Trim any blank spaces from the left and right of the text Check that what you have left i… Read More
  • Create a database with phpMyAdmin You can create all of your database tables and queries using PHP code. But before doing that, it's a good idea to get an understanding of just what it is you'll be creating. If you're new to the world of databases, the… Read More
  • PHP Functions and Arguments Arguments Functions can be handed variables, so that you can do something with what's inside of them. You pass the variable over to your functions by typing them inside of the round brackets of the function name… Read More
  • Getting values out of PHP functions When you're creating your own functions, you may notice that they can be broken down in to two categories: functions that you can leave, and just let them do their jobs; and functions where you need to get an answer ba… Read More

1 comment: