PHP math operations and operators
PHP math operations and operators
PHP is a very powerful language that can help you to perform mathematical operations really easy. Math expressions are made up of operators and operands. You can perform easy operations like adding, subtracting, multiplying or dividing with PHP. Even comparison operators can be used with this language (greater than, less than, equal with).
Let’s see some examples with possible operation that you can perform in PHP.
Basic operations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$a = 2; $b = 3; $c = 6; //Adding two or more numbers: echo $a + $b; //outputs 5 //Subtracting two or more numbers: echo $b - $a; //outputs 1 //Multiplying two or more numbers: echo $a * $b; //outputs 6 //Dividing two or more numbers: echo $c / $a; //outputs 3 |
Comparison operations
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$a = 2; $b = 6; $c = 2; if ( $a < $b ) { echo 'Variable "a" is smaller than variable "b". <br />'; } elseif ( $a > $b ) { echo 'Variable "a" is bigger than variable "b" <br />'; } if ( $a == $c ) { echo 'Variable "a" is equal to variable "c. <br />'; } |
Other types of operations
Rounding numbers:
In PHP you can round numbers in three different ways. One is the classic one, in which everything that is .5 or over will be rounded up. You can also use ceil to round everything up, or floor to round everything down.
1 2 3 |
echo(round(0.30) . "<br />"); //0 echo(ceil(0.60) . "<br />"); //1 echo(floor(0.80) . "<br />"); //0 |
Sine, cosine or tangent
1 2 3 |
echo sin(60); //-0.304810621 echo cos(60); //-0.95241298041516 echo tan(60); //0.32004038937956 |
Number formatting
1 2 |
number_format (1234.567); //Returns the number 1,235 number_format (1234.567, 2); //Returns the number 1,234.57 |
Min or max
Min – If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values.
Max – If the first and only parameter is an array, max() returns the highest value in that array. If at least two parameters are provided, max() returns the biggest of these values.
1 2 |
echo min(2, 4, 6, 8); // Returns 2 echo max(2, 4, 6, 8); // Returns 8 |
Summary
PHP is a very easy to use language when it comes to math. It is very suggestive and yet powerful. There are plenty of other things that you can perform in different situations. We covered only a few of them here in this article, for the sake of enumerating few possibilities that you have with this language.