unexpected NAN value was coerced to %s¶
Description¶
When a NAN (Not a Number) float value is coerced to another type such as int or string, PHP emits this warning. NAN is a special float value that represents an undefined or unrepresentable result of a floating-point operation.
Coercing NAN to int produces 0, and coercing it to string produces an empty string. These results are misleading since NAN is not equivalent to zero or empty. The warning alerts developers that a NAN value is silently converted, which is almost certainly unintended.
NAN is produced by operations like acos(8), log(-1), sqrt(-1), or 0.0/0.0.
Example¶
<?php
// NAN coerced to int
$a = (int) NAN;
// $a = 0
// NAN coerced to string
$b = (string) NAN;
// $b = ""
// NAN passed to an integer parameter
function foo(int $x) {}
foo(NAN);
?>
Literal Examples¶
unexpected NAN value was coerced to int
unexpected NAN value was coerced to string
Solutions¶
Check for
is_nan()before coercing or passing the value to a typed parameter.Handle
NANexplicitly at its source by validating the result of math operations.Use
is_finite()to filter out bothNANandINFbefore using a float value.
See Also¶
Changed Behavior¶
This error may appear following an evolution in behavior, in previous versions. See ` <https://php-changed-behaviors.readthedocs.io/en/latest/behavior/.html>`_.