Arithmetic Operators
PHP, a widely-used open source scripting language, is full of operators which are used to perform operations on variables and values. In this tutorial, we will focus on one of the most fundamental parts of PHP or any other programming language for that matter, known as 'Arithmetic Operators'.
What are Arithmetic Operators?
Arithmetic operators are used to perform arithmetic/mathematical operations on operands. An operand can be a value or a variable. The basic arithmetic operators in PHP are:
- Addition (
+
) - Subtraction (
-
) - Multiplication (
*
) - Division (
/
) - Modulus (
%
) - Exponentiation (
**
)
Let's dive into each one of these.
Addition (+
)
The addition operator (+
) adds two numbers together.
<?php
$x = 10;
$y = 6;
echo $x + $y; // Outputs: 16
?>
Subtraction (-
)
The subtraction operator (-
) subtracts one number from another.
<?php
$x = 10;
$y = 6;
echo $x - $y; // Outputs: 4
?>
Multiplication (*
)
The multiplication operator (*
) multiplies two numbers.
<?php
$x = 10;
$y = 6;
echo $x * $y; // Outputs: 60
?>
Division (/
)
The division operator (/
) divides one number by another.
<?php
$x = 10;
$y = 2;
echo $x / $y; // Outputs: 5
?>
Modulus (%
)
The modulus operator (%
) returns the remainder of a division.
<?php
$x = 10;
$y = 3;
echo $x % $y; // Outputs: 1
?>
Exponentiation (**
)
The exponentiation operator (**
) raises the first operand to the power of the second operand.
<?php
$x = 10;
$y = 2;
echo $x ** $y; // Outputs: 100
?>
These are the basic arithmetic operators in PHP. They are quite straightforward and function similarly to how they do in standard mathematics.
It's worth noting that PHP supports both post-incrementing ($x++
) and pre-incrementing (++$x
), as well as post-decrementing ($x--
) and pre-decrementing (--$x
). These can be useful for various operations in your PHP scripts.
Don't hesitate to play around with these operators and try different numbers and operations. The best way to learn programming is by doing, so experiment with these operators and see what happens. Happy coding!