W3docs

fmod()

Today, we will discuss the fmod() function in PHP. This function is used to get the remainder of a division operation between two numbers.

Today, we will discuss the fmod() function in PHP. This function is used to get the remainder of a division operation between two numbers.

What is the fmod() Function?

The fmod() function in PHP is a built-in function that is used to get the remainder of a division operation between two numbers. The function takes two numbers as input and returns the remainder of the division operation as a floating-point number.

Syntax and Parameters

fmod(float $num1, float $num2): float
  • $num1: The dividend.
  • $num2: The divisor.

Return Value: Returns the floating-point remainder of $num1 / $num2. If $num2 is 0, the function returns NAN.

How to Use the fmod() Function

Using the fmod() function in PHP is very simple. Here is an example of how to use the function:

How to Use the fmod() Function in PHP?

<?php
$number1 = 5;
$number2 = 2;

// Get the remainder of the division operation using the fmod() function
$remainder = fmod($number1, $number2);

// Output the remainder
echo $remainder;
?>

In this example, we set two numbers as variables. We then call the fmod() function with the two numbers as parameters to get the remainder of the division operation. Finally, we output the remainder to the screen. The exact output is 1.

Comparison with the % Operator

While the % operator also calculates remainders, it only works with integers. The fmod() function works with both integers and floating-point numbers, making it more versatile for mathematical calculations involving decimals.

Edge Cases

  • Negative Operands: fmod() preserves the sign of the dividend. For example, fmod(-5, 2) returns -1.
  • Division by Zero: If the divisor is 0, fmod() returns NAN (Not a Number) instead of throwing an error.

Conclusion

The fmod() function in PHP is a useful tool for any PHP developer working with division operations. By using this function, you can get the remainder of a division operation between two numbers, which can be useful in a variety of applications. We hope that this guide has been helpful in understanding how to use the fmod() function in your PHP code. It is particularly handy for tasks like time math, cyclic array indexing, and handling decimal remainders where the % operator falls short.

Practice

Practice

What is the function of the fmod() function in PHP?