RandomCompat_intval

Cast to an integer if we can, safely.

Description

(int) RandomCompat_intval( (number) $number, (constant) $fail_open = false ); 

If you pass it a float in the range (~PHP_INT_MAX, PHP_INT_MAX) (non-inclusive), it will sanely cast it to an int. If you it's equal to ~PHP_INT_MAX or PHP_INT_MAX, we let it fail as not an integer. Floats lose precision, so the <= and => operators might accidentally let a float through.

Returns (int)

(or float if $fail_open)

Parameters (2)

0. $number (number)
The number we want to convert to an int
1. $fail_open — Optional. (constant) => false
Set to true to not throw an exception

Usage

  1. if ( !function_exists( 'RandomCompat_intval' ) ) { 
  2. require_once ABSPATH . WPINC . '/random_compat/cast_to_int.php'; 
  3.  
  4. // The number we want to convert to an int 
  5. $number = null; 
  6.  
  7. // Set to true to not throw an exception 
  8. $fail_open = false; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = RandomCompat_intval($number, $fail_open); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/random_compat/cast_to_int.php  
  1. function RandomCompat_intval($number, $fail_open = false) 
  2. if (is_numeric($number)) { 
  3. $number += 0; 
  4.  
  5. if ( 
  6. is_float($number) 
  7. && 
  8. $number > ~PHP_INT_MAX 
  9. && 
  10. $number < PHP_INT_MAX 
  11. ) { 
  12. $number = (int) $number; 
  13.  
  14. if (is_int($number) || $fail_open) { 
  15. return $number; 
  16.  
  17. throw new TypeError
  18. 'Expected an integer.' 
  19. );