Logical operations exist in all programming languages ββand PHP is no exception. In addition to simple division, multiplication, addition or subtraction, there are integer and residual divisions, which we will talk about now, as well as we will analyze them using detailed examples.
Integer division is the derivation of the integer part from division. For example, if we divide 5 by 2, we get 2, not 2.5.
With residual division everything is different. This is the output of the remainder of the division by an integer. For example, dividing the same five, you get not 2, but 1, because dividing 5 by 2, we get 2, and the remainder is 1.
How to do integer division in PHP
For example, in Python, this division occurs using a simple operator: "//".
But in PHP it will not be so easy to do, but still the process does not require superknowledge of the language.
We give an example of how this can be implemented.
In PHP seventh version, the function is as follows:
intdiv();
In an older version, the same function looks like this:
int();
There is also a way for all versions:
floor();
How to issue?
For example, take the first function, all the rest are performed in approximately the same way.
$result = intdiv(10, 3); echo $result;
Residual division in PHP
In order to output the integer remainder from division in PHP, just put the operator "%".
You can see an example code below.
$i = 10 % 3; echo $i;
As we see, everything is quite simple and does not require long explanations.
Where can i apply?
Knowledge of integer division in PHP will be very useful if you need to compare two numbers, create a flip number (a popular exercise), or, for example, a program called FizzBuzz. Its essence is that you have to write a cycle from 1 to 100, which divides each number by 3 and 5. If the number divided by 3, the remainder gives 0, then write Fizz, if divided by 5, then Buzz, and if By dividing both 5 and 3, in the remainder we get 0, then we write FizzBuzz. This is a very popular job in interviews. If you completed it yourself, you can be proud of yourself.
Or, for example, we have to derive from its number 452 all its numbers (4, 5, 2).
Conclusion
Of course, integer and residual divisions are useful and quite common, they are not as convenient to use as in Python, but still important.
Now you are one step closer to learning the PHP programming language, and in the future you will become even closer if you are also working hard to overcome difficulties.