RandomCompat_intval( int|float $number, bool $fail_open = false )

Cast to an integer if we can, safely.


Description Description

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.


Parameters Parameters

$number

(int|float) (Required) The number we want to convert to an int

$fail_open

(bool) (Optional) Set to true to not throw an exception

Default value: false


Top ↑

Return Return

(float|int)


Top ↑

Source Source

File: wp-includes/random_compat/cast_to_int.php

    function RandomCompat_intval($number, $fail_open = false)
    {
        if (is_int($number) || is_float($number)) {
            $number += 0;
        } elseif (is_numeric($number)) {
            $number += 0;
        }

        if (
            is_float($number)
            &&
            $number > ~PHP_INT_MAX
            &&
            $number < PHP_INT_MAX
        ) {
            $number = (int) $number;
        }

        if (is_int($number)) {
            return (int) $number;
        } elseif (!$fail_open) {
            throw new TypeError(
                'Expected an integer.'
            );
        }
        return $number;
    }


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.