Modulus operator in PHP
Here we are going to learn the basic concepts about the modulus operator in PHP. It is an integer operator and it finds out the remainder after an integer division of the two integers. Basically the result shows up the remainder in an integer form. PHP consists of eight arithmetic operators such as addition(+), subtraction(-), division (/), multiplication(*), modulo(%). Here we will focus mostly on the modulo operator and its uses.
Basic Calculation :
As we learned above that the modulo operator returns the remainder of the division of two integers. Let us look at an example:
<?Php echo 25 % 2; ?>
*The sign (positive/negative) of the divisor doesn’t affect the sign of the result. It is only affected by the sign of the dividend.
Example of modulus operator in PHP
We can also calculate the division of floating numbers and getting the remainder as a result in the form of floating numbers for an example:
<?Php echo 8.5%2; ?>
But, to get the results in float form we need to add one function i.e,
<?php echo fmod(8.5, 2); ?>
Now we will discuss the uses of this Modulo operator:
1> The topmost necessity of this operator is to check one integer is divisible with another given integer or not. If the remainder comes up as “0 “that means both of the numbers are divisible.
2> To evaluate the input is even or odd, by checking at the remainder “0”.
3>Modulo also acts as a limit in some cases, for example, positive numbers will return a number between 0 and N -1, where N is the divisor. It restricts the input number for not exceeding the given limit.
4>In some activities, it can be also used as a loop for a provided limit.
Henceforth we conclude this modulo operator is very easy to use and has many useful applications in PHP as well as in other coding languages.