Use fmod() when you need to returns the floating-point remainder of a division in a PHP application. The examples below show the actual operation and its limitations.
What Is fmod() in PHP?
Returns the floating-point remainder of a division. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
fmod(float $num1, float $num2): float
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
echo fmod(7.5, 2.0);
Output:
1.5
Example 2: Different Input or Behavior
<?php
echo fmod(-7.5, 2.0);
Output:
-1.5
Practical Example: Applying the Function
<?php
$angles = [370.5, 725.25]; foreach ($angles as $angle) { echo fmod($angle, 360.0) . PHP_EOL; }
Output:
10.5
5.25
Important Behavior and Edge Cases
A zero divisor is invalid; floating-point representation may limit exactness.
Comparison With Related Functions
| Approach | Difference |
|---|---|
fmod() | Returns the floating-point remainder of a division. |
| Related operation | % performs integer remainder; fmod() works with floating-point values. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | A zero divisor is invalid; floating-point representation may limit exactness. |
| Confusing this function with a related operation | % performs integer remainder; fmod() works with floating-point values. |
Key Takeaways
- Returns the floating-point remainder of a division.
- A zero divisor is invalid; floating-point representation may limit exactness.
- % performs integer remainder; fmod() works with floating-point values.
Use fmod() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.