3v4l.org

run code in 300+ PHP versions simultaneously
<?php // conditionally define PHP_INT_MIN since PHP 5.x doesn't // include it and it's needed to validate integer casts if (!defined("PHP_INT_MIN")) { define("PHP_INT_MIN", ~PHP_INT_MAX); } var_dump(to_int((float) PHP_INT_MAX) === PHP_INT_MAX); /** * Returns the value as an int, or false if it cannot be safely cast * @param mixed $val * @return int */ function to_int($val) { switch (gettype($val)) { case "integer": return $val; case "double": if (!is_infinite($val) && !is_nan($val) && $val >= PHP_INT_MIN) { // due to rounding issues, on 64-bit platforms // the float must be less than PHP_INT_MAX if ( (PHP_INT_SIZE === 8 && $val < PHP_INT_MAX) || // valid 64-bit (PHP_INT_SIZE !== 8 && $val <= PHP_INT_MAX) // valid non-64-bit ) { return (int) $val; // valid floats should cast } } return false; case "string": $val = trim($val, " \t\n\r\v\f"); // trim whitespace return filter_var($val, FILTER_VALIDATE_INT); default: return false; } }
Output for 4.4.0 - 4.4.9, 5.0.5, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.24 - 5.5.35, 5.6.8 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.10, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
bool(false)
Output for 4.3.0 - 4.3.11, 5.0.0 - 5.0.4
Notice: Use of undefined constant PHP_INT_MAX - assumed 'PHP_INT_MAX' in /in/A4TIW on line 6 Notice: Use of undefined constant PHP_INT_MAX - assumed 'PHP_INT_MAX' in /in/A4TIW on line 9 Notice: Use of undefined constant PHP_INT_SIZE - assumed 'PHP_INT_SIZE' in /in/A4TIW on line 27 Notice: Use of undefined constant PHP_INT_SIZE - assumed 'PHP_INT_SIZE' in /in/A4TIW on line 28 Notice: Use of undefined constant PHP_INT_MAX - assumed 'PHP_INT_MAX' in /in/A4TIW on line 28 Notice: Use of undefined constant PHP_INT_MAX - assumed 'PHP_INT_MAX' in /in/A4TIW on line 9 bool(false)

preferences:
184.58 ms | 403 KiB | 310 Q