Иван Божков
Иван Божков

Reputation: 264

PHP function to validate if number is in range

I want to create a function that checks if number is in range.

// ex. validate(10,"? >=0 && ? <= 30)
function validate($var,$range){
    //check if $var is a number
    {
        //check if $range contains '?'
        {
            //replace '?' with $var in $range
            // how to execute the if statement in $range to check it and return true or false?
        }
    }
}

That's my idea of it.. If you have something better in mind please make a suggestion.

Upvotes: 0

Views: 527

Answers (1)

rink.attendant.6
rink.attendant.6

Reputation: 46218

This solutions seems to be more flexible. I've even documented it.

/**
 * Validate a number between a given range
 * @param int|double $num The number to validate
 * @param int|double $min The lower boundary of the range
 * @param int|double $max The upper boundary of the range
 * @param boolean $inclusive Whether to include the boundary values as valid
 * @return boolean
 */
function validate($num, $min, $max = PHP_INT_MAX, $inclusive = true) {

    if ($inclusive) {
       return $num >= $min && $num <= $max;
    }

    return $num > $min && $num < $max;
}

Upvotes: 1

Related Questions