Saturday, February 22, 2014

Numeric Functions

This week's post will take a closer look at numeric data types within PHP. Specifically, it will explore some of the built in operators and functions that are commonly used with each.

Numbers:

PHP supports all of the basic mathematical operations that are found within most other programming languages. Here are a few examples;

$q=5; 
$r=3;

-------

  • $z=$q * $r Multiplication
  • $z=$q / $r division
  • $z=$q + $r Addition
  • $z=$q - $r  subtraction
  • $z=$q % $r remainder calculation


These  calculations can be stored in a variable  for later printing/returning like in the examples above. Conveniently, PHP also allows you to directly print or return the results of the calculations:


  • echo ($x % $y); 



Interestingly enough, PHP also has quite an extensive mathematical library that can be used for more advanced calculations. Usually, when I think of a web based programming language, I don't associate it with programs that require advanced mathematical calculations. Here are a few examples of the more advanced operations;


  • $z=abs($z) Absolute Value
  • $z=sqrt($q) Square Root
  • $z=sin/cos/tan($q) Trig Functions
  • $z=ceil($q) round decimal up to nearest whole number
  • $z=floor($q) round decimal down to nearest whole number



Another interesting fact about  equations in PHP is that even the more advanced calculations are part of the PHP core library. From a user's perspective, this means that there is no importing needed. This is something that isn't often seen in other object oriented languages, as Very few of them include anything other than basic addition/subtraction/multiplication/division without importation.






No comments:

Post a Comment