Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The % operator in PHP is the arithmetic modulo (or integer remainder) operator. It evaluates the remainder of the integer division between a dividend (left operand) and a divisor (right operand).
$remainder = $dividend % $divisor;

Operand Evaluation and Type Coercion

Before the modulo operation is executed, PHP implicitly casts both operands to integers. This casting process strips the fractional part of floating-point numbers (truncation towards zero) rather than rounding them. As of PHP 8.1.0, implicitly casting a float with a fractional part to an integer emits a deprecation warning. To perform an integer modulo on floating-point numbers without triggering this warning, operands must be explicitly cast to integers.
// PHP 8.1+: Emits "Deprecated: Implicit conversion from float to int loses precision"
// 5.9 truncates to 5, 2.3 truncates to 2
$implicit = 5.9 % 2.3; // Evaluates as 5 % 2, returning 1

// Explicit casting prevents the deprecation warning
$explicit = (int)5.9 % (int)2.3; // Returns 1

Sign Determination

The sign of the resulting remainder is strictly determined by the dividend. The sign of the divisor is ignored during the evaluation.
$a =  5 %  3; // Returns  2
$b =  5 % -3; // Returns  2 (Divisor sign is ignored)
$c = -5 %  3; // Returns -2 (Takes dividend sign)
$d = -5 % -3; // Returns -2 (Takes dividend sign)

Division by Zero

If the divisor evaluates to 0 (either explicitly or after float-to-integer truncation), PHP throws a DivisionByZeroError exception.
$result = 10 % 0; // Throws DivisionByZeroError

// PHP 8.1+: Emits deprecation warning for 0.8, then throws DivisionByZeroError 
// because 0.8 truncates to 0
$result = 10 % 0.8; 

Floating-Point Modulo Alternative

Because the % operator forces integer casting, it cannot be used to calculate the remainder of floating-point division. For exact floating-point modulo operations without truncation or deprecation warnings, PHP provides the built-in fmod() function.
// % operator (Emits deprecation warning in PHP 8.1+, truncates to 5 % 1)
$intMod = 5.7 % 1.3; // Returns 0

// fmod() function (Preserves floating-point precision, no warnings)
$floatMod = fmod(5.7, 1.3); // Returns 0.5
Master PHP with Deep Grasping Methodology!Learn More