Php numbers in range

How to validate an integer within a range in PHP

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

Problem statement: Given an integer, check if that integer is within the given range.

The filter_var() function

The filter_var() function in PHP is used to validate/filter a variable according to the specified filter.

Syntax

filter_var(var, filtername, options) 

Parameters

  • var : The variable to be evaluated.
  • filtername : The name of the filter to use. This is an optional parameter.
  • options : Flags/options to use. This is an optional parameter.

Return value

The method returns the filtered data on successful. Otherwise, it returns false on failure.

The FILTER_VALIDATE_INT filter

The FILTER_VALIDATE_INT filter is used to check if the value is an integer. The filter optionally accepts a range when specified checks if the given integer value is within the range.

The options to specify for range check are as follows:

  • min_range : This specifies the minimum value in the integer range.
  • max_range : This specifies the maximum value in the integer range.

By combining filter_var() and FILTER_VALIDATE_INT , we can check if the given number is within the given range.

Источник

range

If a step value is given, it will be used as the increment (or decrement) between elements in the sequence. step must not equal 0 and must not exceed the specified range. If not specified, step will default to 1.

Return Values

Returns an array of elements from start to end , inclusive.

Examples

Example #1 range() examples

// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach ( range ( 0 , 12 ) as $number ) echo $number ;
>

// The step parameter
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach ( range ( 0 , 100 , 10 ) as $number ) echo $number ;
>

// Usage of character sequences
// array(‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’);
foreach ( range ( ‘a’ , ‘i’ ) as $letter ) echo $letter ;
>

// array(‘c’, ‘b’, ‘a’);
foreach ( range ( ‘c’ , ‘a’ ) as $letter ) echo $letter ;
>
?>

Notes

Note:

Character sequence values are limited to a length of one. If a length greater than one is entered, only the first character is used.

See Also

User Contributed Notes 29 notes

To create a range array like

combine two range arrays using array_combine:

So with the introduction of single-character ranges to the range() function, the internal function tries to be «smart», and (I am inferring from behavior here) apparently checks the type of the incoming values. If one is numeric, including numeric string, then the other is treated as numeric; if it is a non-numeric string, it is treated as zero.

Читайте также:  Python get request with params

If you pass in a numeric string in such a way that is is forced to be recognized as type string and not type numeric, range() will function quite differently.

echo implode ( «» , range ( 9 , «Q» ));
// prints 9876543210

echo implode ( «» , range ( «9 » , «Q» )); //space after the 9
// prints 9:;?@ABCDEFGHIJKLMNOPQ

echo implode ( «» , range ( «q» , «9 » ));
// prints qponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@ ?> =?>

I wouldn’t call this a bug, because IMO it is even more useful than the stock usage of the function.

The function «range» is very useful to get an array of characters as range(‘C’,’R’) does.

At work, I had to extend the function range($a,$b) to work in this special case: with two uppercase strings $a and $b, it should return all the possible strings between $a and $b.
This could be used for example to get the excel column indexes.
e.g. array( ‘A’ , ‘B’ , ‘C’ . ‘Z’ , ‘AA’ , ‘AB’ , ‘AC’ , ‘AD’ ) ?>

So I wrote the function getrange($min,$max) that exactly does this.

function getcolumnrange ( $min , $max ) $pointer = strtoupper ( $min );
$output =array();
while( positionalcomparison ( $pointer , strtoupper ( $max )) <= 0 )array_push ( $output , $pointer );
$pointer ++;
>
return $output ;
>

function positionalcomparison ( $a , $b ) $a1 = stringtointvalue ( $a ); $b1 = stringtointvalue ( $b );
if( $a1 > $b1 )return 1 ;
else if( $a1 < $b1 )return - 1 ;
else return 0 ;
>

/*
* e.g. A=1 — B=2 — Z=26 — AA=27 — CZ=104 — DA=105 — ZZ=702 — AAA=703
*/
function stringtointvalue ( $str ) $amount = 0 ;
$strarra = array_reverse ( str_split ( $str ));

for( $i = 0 ; $i < strlen ( $str ); $i ++)$amount +=( ord ( $strarra [ $i ])- 64 )* pow ( 26 , $i );
>
return $amount ;
>
?>

The function will generate an array of integers even if your numerical parameters are enclosed in quotes.
var_dump ( range ( ‘1’ , ‘2’ ) ); // outputs array(2) < [0]=>int(1) [1]=> int(2) >
?>

An easy way to get an array of strings is to map strval() to the range:
var_dump ( array_map ( ‘strval’ , range ( ‘1’ , ‘2’ )) ); // outputs array(2) < [0]=>string(1) «1» [1]=> string(1) «2» >
?>

You might expect range($n, $n-1) to be an empty array (as in e.g. Python) but actually PHP will assume a step of -1 if start is larger than end.

function natural_prime_numbers (array $range , bool $print_info = false ) : array $start_time = time ();
$primes_numbers = array();
$print = » ;
$count_range = count ( $range );
foreach( $range as $number ) $values_division_number = array();
if( $number === 0 || $number === 1 || ! is_int ( $number )) < // eliminate 0, 1 and other no integer
continue;
>
if( $number != 2 && $number % 2 === 0 ) < // eliminate 2 and pairs numbers
continue;
>
for( $i = 1 ; $i <= $number ; $i ++)$resultado_divisao = $number / $i ;
$values_division_number [ $i ] = $resultado_divisao ;

if( $count_range $print .= PHP_EOL ;
$info = ‘The number ‘ . $number . ‘ divided by the number ‘ . $i . ‘ is equal to: ‘ .( $number / $i );
$print .= $info ;
if( $i === $number ) $print .= PHP_EOL ;
>
>

$values_division_number = array_values ( $values_division_number ); // reindex array

// here we want only array with 2 indexes with the values 1 and own number (rule to a natural prime number)
if( count ( $values_division_number ) === 2 && $values_division_number [ 0 ] === $number && $values_division_number [ 1 ] === 1 ) $primes_numbers [ $number ] = $number ;
>

>
>
return array(
‘length_prime_numbers’ => count ( $primes_numbers ),
‘prime_numbers’ => array_values ( $primes_numbers ),
‘print’ => $print ,
‘total_time_processing’ => ( time () — $start_time ). ‘ seconds.’ ,
);
>
var_dump ( natural_prime_numbers ( range ( 0 , 11 ))); // here the range() function 😉

Читайте также:  What is javascript html dom

// Result:
// array (size=3)
// ‘length_prime_numbers’ => int 5
// ‘prime_numbers’ =>
// array (size=5)
// 0 => int 2
// 1 => int 3
// 2 => int 5
// 3 => int 7
// 4 => int 11
// ‘print’ => string ‘
// O número 2 dividido pelo número 1 é igual a: 2
// O número 2 dividido pelo número 2 é igual a: 1

// O número 3 dividido pelo número 1 é igual a: 3
// O número 3 dividido pelo número 2 é igual a: 1.5
// O número 3 dividido pelo número 3 é igual a: 1

// O número 5 dividido pelo número 1 é igual a: 5
// O número 5 dividido pelo número 2 é igual a: 2.5
// O número 5 dividido pelo número 3 é igual a: 1.6666666666667
// O número 5 dividido pelo número 4 é igual a: 1.25
// O número 5 dividido pelo ‘.

// **************************** //
//
// * Remember that the function is recursive, that is: a range of 5000 takes more than 1 minute on a processor Intel® Core™ i5-8250U (3.40 GHz).
//
// **************************** //
?>

Источник

How to check if an integer is within a range of numbers in PHP?

How can I check if a given number is within a range of numbers?

Php Solutions

Solution 1 — Php

will be true if $value is between $min and $max , inclusively

See the PHP docs for more on comparison operators

Solution 2 — Php

filter_var( $yourInteger, FILTER_VALIDATE_INT, array( 'options' => array( 'min_range' => $min, 'max_range' => $max ) ) ); 

This will also allow you to specify whether you want to allow octal and hex notation of integers. Note that the function is type-safe. 5.5 is not an integer but a float and will not validate.

Detailed tutorial about filtering data with PHP:

Solution 3 — Php

if ( in_array(2, range(1,7)) ) < echo 'Number 2 is in range 1-7'; > 

Solution 4 — Php

You could whip up a little helper function to do this:

/** * Determines if $number is between $min and $max * * @param integer $number The number to test * @param integer $min The minimum value in the range * @param integer $max The maximum value in the range * @param boolean $inclusive Whether the range should be inclusive or not * @return boolean Whether the number was in the range */ function in_range($number, $min, $max, $inclusive = FALSE) < if (is_int($number) && is_int($min) && is_int($max)) < return $inclusive ? ($number >= $min && $number $max) : ($number > $min && $number < $max) ; > return FALSE; > 

And you would use it like so:

var_dump(in_range(5, 0, 10)); // TRUE var_dump(in_range(1, 0, 1)); // FALSE var_dump(in_range(1, 0, 1, TRUE)); // TRUE var_dump(in_range(11, 0, 10, TRUE)); // FALSE // etc. 

Solution 5 — Php

if (($num >= $lower_boundary) && ($num $upper_boundary))  

You may want to adjust the comparison operators if you want the boundary values not to be valid.

Solution 6 - Php

You can try the following one-statement:

Solution 7 - Php

Some other possibilities:
if (in_array($value, range($min, $max), true)) < echo "You can be sure that $min $value $max"; > 
Or:
if ($value === min(max($value, $min), $max)) < echo "You can be sure that $min $value $max"; > 

Actually this is what is use to cast a value which is out of the range to the closest end of it.

$value = min(max($value, $min), $max); 
Example
/** * This is un-sanitized user input. */ $posts_per_page = 999; /** * Sanitize $posts_per_page. */ $posts_per_page = min(max($posts_per_page, 5), 30); /** * Use. */ var_dump($posts_per_page); // Output: int(30) 

Solution 8 - Php

 switch ($num)< case ($num>= $value1 && $num$value2): echo "within range 1"; break; case ($num>= $value3 && $num$value4): echo "within range 2"; break; . . . . . default: //default echo "within no range"; break; > 

Solution 9 - Php

Another way to do this with simple if/else range. For ex:

$watermarkSize = 0; if (($originalImageWidth >= 0) && ($originalImageWidth $watermarkSize = 10; > else if (($originalImageWidth >= 641) && ($originalImageWidth $watermarkSize = 25; > else if (($originalImageWidth >= 1025) && ($originalImageWidth $watermarkSize = 50; > else if (($originalImageWidth >= 2049) && ($originalImageWidth $watermarkSize = 100; > else < $watermarkSize = 200; > 

Solution 10 - Php

I created a function to check if times in an array overlap somehow:

 /** * Function to check if there are overlapping times in an array of \DateTime objects. * * @param $ranges * * @return \DateTime[]|bool */ public function timesOverlap($ranges) < foreach ($ranges as $k1 => $t1) < foreach ($ranges as $k2 => $t2) < if ($k1 != $k2) < /* @var \DateTime[] $t1 */ /* @var \DateTime[] $t2 */ $a = $t1[0]->getTimestamp(); $b = $t1[1]->getTimestamp(); $c = $t2[0]->getTimestamp(); $d = $t2[1]->getTimestamp(); if (($c >= $a && $c $b) || $d >= $a && $d $b) < return true; > > > > return false; > 

Solution 11 - Php

Here is my little contribution:

function inRange($number) < $ranges = [0, 13, 17, 24, 34, 44, 54, 65, 200]; $n = count($ranges); while($n--)< if( $number > $ranges[$n] ) return $ranges[$n]+1 .'-'. $ranges[$n + 1]; > 

Solution 12 - Php

I have function for my case

echo checkRangeNumber(0); echo checkRangeNumber(1); echo checkRangeNumber(499); echo checkRangeNumber(500); echo checkRangeNumber(501); echo checkRangeNumber(3001); echo checkRangeNumber(999); 
0 1-500 1-500 1-500 501-1000 3000-3500 501-1000 
function checkRangeNumber($number, $per_page = 500) < //$per_page = 500; // it's fixed number, but. if ($number == 0) < return "0"; > $num_page = ceil($number / $per_page); // returns 65 $low_limit = ($num_page - 1) * $per_page + 1; // returns 32000 $up_limit = $num_page * $per_page; // returns 40 return "$low_limit-$up_limit"; > 

Solution 13 - Php

function limit_range($num, $min, $max) < // Now limit it return $num>$max?$max:$num$min?$min:$num; > $min = 0; // Minimum number can be $max = 4; // Maximum number can be $num = 10; // Your number // Number returned is limited to be minimum 0 and maximum 4 echo limit_range($num, $min, $max); // return 4 $num = 2; echo limit_range($num, $min, $max); // return 2 $num = -1; echo limit_range($num, $min, $max); // return 0 

Solution 14 - Php

$ranges = [ 1 => [ 'min_range' => 0.01, 'max_range' => 199.99 ], 2 => [ 'min_range' => 200.00, ], ]; foreach($ranges as $value => $range)< if(filter_var($cartTotal, FILTER_VALIDATE_FLOAT, ['options' => $range]))< return $value; > > 

Solution 15 - Php

Thank you so much and I got my answer by adding a break in the foreach loop and now it is working fine.

Here are the updated answer:

foreach ($this->crud->getDataAll('shipping_charges') as $ship) < if ($weight >= $ship->low && $weight $ship->high) < $val = $ship->amount; break; > else < $val = 900; > > echo $val ; 

Источник

Оцените статью