Divides floating-point numbers using IEEE 754 rules instead of throwing for zero divisors.
What Is fdiv() in PHP?
Divides floating-point numbers using IEEE 754 rules instead of throwing for zero divisors.
Its syntax is:
fdiv(float $num1, float $num2): float
Parameters:
$num1— Accepted as float; required argument.$num2— Accepted as float; required argument.
Return type: float. Dividing by zero returns INF, -INF or NAN; validate results before persisting calculations.
Availability: Available in PHP 8.0+.
Example 1: Basic Usage
<?php
var_dump(fdiv(10, 2));
Output:
float(5)
Dividing by zero returns INF, -INF or NAN; validate results before persisting calculations.
Example 2: A Different Input
<?php
var_dump(is_infinite(fdiv(1, 0)));
Output:
bool(true)
Dividing by zero returns INF, -INF or NAN; validate results before persisting calculations.
Practical Example: Applying It in a Program
<?php
$ratios = [[10, 2], [1, 0], [0, 0]]; foreach ($ratios as [$numerator, $denominator]) { $result = fdiv($numerator, $denominator); echo is_nan($result) ? "NaN" : (is_infinite($result) ? "Infinite" : (string) $result); echo PHP_EOL; }
Output:
5
Infinite
NaN
Dividing by zero returns INF, -INF or NAN; validate results before persisting calculations.
Important Behavior and Edge Cases
- Key behavior: Dividing by zero returns INF, -INF or NAN; validate results before persisting calculations.
- Environment: Available in PHP 8.0+.
Comparison With Related Functions
| Function | Purpose |
|---|---|
fdiv() | Divides floating-point numbers using IEEE 754 rules instead of throwing for zero divisors. |
/ operator | The / operator raises DivisionByZeroError when dividing by zero; fdiv() returns INF, -INF or NAN under IEEE-754 rules. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: Dividing by zero returns INF, -INF or NAN; validate results before persisting calculations | Dividing by zero returns INF, -INF or NAN; validate results before persisting calculations. |
Key Takeaways
- Divides floating-point numbers using IEEE 754 rules instead of throwing for zero divisors.
- Dividing by zero returns INF, -INF or NAN; validate results before persisting calculations.
- Available in PHP 8.0+.
Summary: Dividing by zero returns INF, -INF or NAN; validate results before persisting calculations.