Question

I want to check value with in range or not suppose if I have range D1 to D40 and if I enter D20 then it returns value with in range.

I check several solution but this are for only integer not for both string and integer.

EDIT

Range will be dynamic like AA20 to AA30 or like AC10D to AC30D

Was it helpful?

Solution

You can write something simpler like this...

$arr = range(1,40); //<--- Creating a range of 1 to 40 elements..
array_walk($arr,function (&$v){ $v = 'D'.$v;}); //<--- Concatenating D to all the elements..
echo in_array('D20',$arr) ? 'Found' : 'Not Found'; //<-- The search part.

Demonstration

OTHER TIPS

First, you should remove the letter D from your string variable, like this:

// This is your first variable:
$rang1="D5";

// This is your second rang variable:
$rang2="D20";

$rang1=str_replace("D","",$rang1);
$rang2=str_replace("D","",$rang2);
$rang=$rang2-$rang1;
echo $rang;

Or if your variable looks like this:

$rang="D5 TO D20";

you can use the following:

$rang="D5 TO D20";
$rang=explode(" TO ",$rang);
$rang1=rang[0];
$rang2=rang[1];

$rang1=str_replace("D","",$rang1);
$rang2=str_replace("D","",$rang2);
$rang=$rang2-$rang1;
echo $rang;
// 1. build up array of valid entries
$prefix = "D";
$rangeArray = array();
for($i = 1; $i <= 40; $i++) {
    $rangeArray[] = $prefix . $i;
}

...

// 2. check against that array:
$inRange = in_array($needle, $rangeArray); // boolean

To get the position in the range:

$pos = array_search($needle, $rangeArray); // integer or false if not found

Where $needle would be your input value.

The following code will work with ranges with different letter in the beginning like A10 to B30 (assuming A20 is in that range, but A40 is not):

$min = "A10";
$max = "B30";
$test = "A20";

$min_ascii = chr($min[0]);
$max_ascii = chr($max[0]);
$test_ascii = chr($max[0]);

$min_number = substr($min, 1);
$max_number = substr($max, 1);
$test_number = substr($test, 1);

if ($min_ascii <= $test_ascii and $test_ascii <= $max_ascii
    and $min_number <= $test_number and $test_number <= $max_number)
{
    echo "$test is in the range from $min to $max";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top