How to find a numeric value within a range in php - php

How can I find a value let: 745 is within a range of 0 to 1000 using php?

(0 <= $value && $value <= 1000)

How about using <= and >= ?
$x=745;
$inrange=(0<=$x)&&($x<=1000)

Use a condition
<?php
$val = 745;
if ($val >= 0 && $val <= 1000)
{
// Ok
}
else
{
// Not ok
}

Related

Simplest way to assign numeric ranges to values in php?

I'm trying to create a more simple version of if/else php statements because there are very many of them, so I want to make the code shorter and simpler.
I thought since each outputted value will equal a number going up from 0, then maybe I can do an array, but I'm also open to other solutions.
In human language, I want the value to be one of these numbers between 0 and 4 if it is within different parts of a range of numbers:
// 4 = 10,000+
// 3 = 1000-9,999
// 2 = 500-999
// 1 = 100-499
// 0 = <100
e.g. if $aa is 547, then $zz should equal the numeric value of 2, because it falls within 500-1000.
Now using if/else it's possible, and that works, but I want to make it shorter. Here it is in if/else statements:
if ( $aa >= 10000 ) {
$zz = 4;
} else if ( $aa >= 1000 && $aa < 10000 ) {
$zz = 3;
} else if ( $aa >= 500 && $aa < 1000 ) {
$zz = 2;
} else if ( $aa >= 100 && $aa < 500 ) {
$zz = 1;
} else {
$zz = 0;
}
Now I tried making an array but having trouble figuring out how to do this. Here's what I started with:
$b4 = $aa >= 10000;
$b3 = $aa >= 1000 && $aa < 10000;
$b2 = $aa >= 500 && $aa < 1000;
$b1 = $aa >= 100 && $aa < 500;
$b0 = $aa < 100;
$b_val = array( $b0, $b1, $b2, $b3, $b4 );
This is terribly wrong I know. It's not going to work like that, but maybe there's a way to make it work.
I thought of using switch, but it seems switch isn't designed for this, even though it can be done, and it isn't any shorter. I thought of using ternary, but that doesn't seem shorter either, unless you know how.
How to get a short, crisp, clean code to shorten the if/else statement on ranges of numbers?
You can use a nested ternary working smallest to largest
$zz = $aa < 100 ? 0 : ($aa < 500 ? 1 : ($aa < 1000 ? 2 : ($aa < 10000 ? 3 : 4)));
Demo ~ https://3v4l.org/MnqQv
I'd argue it's not as readable and therefore not as good as a plain old if..elseif..else or a function that returns at the appropriate logic branch.
function getRangeIndex($aa) {
if ($aa < 100) return 0;
if ($aa < 500) return 1;
if ($aa < 1000) return 2;
if ($aa < 10000) return 3;
return 4;
}

calculate specific values of counter inside foreach loop

I am trying to calculate specific values of a counter in my foreach loop.
I have this if statement in my code
if ( $i == 21 || $i == 41 || $i == 61 || $i == 81 || $i == 101 )
which are equal to
($i * 20) + 1
Instead of writing all these values (21,41,61,81...) I want to create a formula for my code but I couldn't figure out what the result should be equal to inside my if statement
Use modulus:
if ($i % 20 == 1) { ...
http://php.net/manual/en/language.operators.arithmetic.php
Look for the remainder after dividing by 20 using the % operator (modulus).
if ($i%20 == 1)
{
// do stuff
}

How to make a correct if-statement to filter out values from a xml-file

Edit 3:
As requested, I'm trying to simplify my question.
Here is a sample of some of my data from a xml file:
<entry>
<title>Entry 1</title>
<f:max_value_a>499 999</f:max_value_a>
<f:max_value_b>999 999</f:max_value_b>
<f:min_value_a>0</f:min_value_a>
<f:min_value_b>500 000</f:min_value_b>
<f:min_value_c>1 000 000</f:min_value_c>
<f:value_for_a>5,10</f:value_for_a>
<f:value_for_b>4,50</f:value_for_b>
<f:value_for_c>3,90</f:value_for_c>
</entry>
<entry>
<title>Entry 2</title>
<f:min_value_a>0</f:min_value_a>
<f:value_for_a>4,20</f:value_for_a>
</entry>
<entry>
<title>Entry 3</title>
<f:max_value_a>1 999 999</f:max_value_a>
<f:min_value_a>100 000</f:min_value_a>
<f:min_value_b>2 000 000</f:min_value_b>
<f:value_for_a>3,735</f:value_for_a>
<f:value_for_b>3,445</f:value_for_b>
</entry>
f:value_for_d is the highest value, and f:value_for_c is lower than d, and so on.
I have a dynamic targetvalue (lets just go with 2 000 000 in this example)
I want to get the value where max_value is greater than the targetvalue, but sometimes max_value is not defined and then set to "0". "0" in max_value should mean unlimited "roof". The min_value can not be greater than targetvalue, but sometimes min_value is not defined and then set to "0". "0" min_value should mean a unlimited "floor".
I have tried with this code
if ($value_for_d > 0 ){
if (($min_value_d <= $targetvalue) xor ($min_value_d == 0)){
if (($max_value_d >= $targetvalue) xor ($max_value_d == 0)){
$query_result = TRUE;
$value = $value_for_d;
}
}
}elseif ($value_for_c > 0 ){
if (($min_value_c <= $targetvalue) xor ($min_value_c == 0)){
if (($max_value_c >= $targetvalue) xor ($max_value_c == 0)){
$query_result = TRUE;
$value = $value_for_c;
}
}
}elseif ($value_for_b > 0 ){
if (($min_value_b <= $targetvalue) xor ($min_value_b == 0)){
if (($max_value_b >= $targetvalue) xor ($max_value_b == 0)){
$query_result = TRUE;
$value = $value_for_b;
}
}
}elseif ($value_for_a > 0 ){
if (($min_value_a <= $targetvalue) xor ($min_value_a == 0)){
if (($max_value_a >= $targetvalue) xor ($max_value_a == 0)){
$query_result = TRUE;
$value = $value_for_a;
}
}
}
If I run this code with a targetvalue of "2 000 000", I get this result:
Entry 1 - 3.9 (correct value is 3.9)
Entry 2 - 0 (correct value is 4.2)
Entry 3 - 3.445 (correct value is 3.445)
If I set the targetvalue to even lower, to 500 000, I get 0 on all my entries.
Edit 4:
If I do:
var_dump($min_value_d,$max_value_d,$min_value_c,$max_value_c,$min_value_b,$max_‌​value_b,$min_value_a,$max_value_a);
I get this output: https://dpaste.de/DtjhO/
If the regions are always exclusive and always in the right order, I'd suggest you do something like this:
<?php
if($min_value_d <= $targetvalue) {
$value = $value_for_d;
} else if($min_value_c <= $targetvalue) {
$value = $value_for_c;
} else if($min_value_b <= $targetvalue) {
$value = $value_for_b;
} else if($min_value_b <= $targetvalue) {
$value = $value_for_b;
}
?>
However, if they are not always exclusive, you should be returning some form of array, as it may fulfil multiple criteria:
Assuming that $min_value_x is not set when it is not in the XML (As in, no minimum) and $max_value_x is not set when it is not in the XML (As in, no maximum)
<?php
$values = array();
//if (there is no minimum or its smaller than target) and (there is no maximum or its larger than target) and at least one of them is non-null
if((is_null($min_value_d) || preg_replace('/([^0-9.])/i', '',$min_value_d) <= $targetvalue) && (is_null($max_value_d) || preg_replace('/([^0-9.])/i', '',$max_value_d) >= $targetvalue) && !(is_null($min_value_d) && is_null($max_value_d))) $values[] = $value_for_d;
if((is_null($min_value_c) || preg_replace('/([^0-9.])/i', '',$min_value_c) <= $targetvalue) && (is_null($max_value_c) || preg_replace('/([^0-9.])/i', '',$max_value_c) >= $targetvalue) && !(is_null($min_value_c) && is_null($max_value_c))) $values[] = $value_for_c;
if((is_null($min_value_b) || preg_replace('/([^0-9.])/i', '',$min_value_b) <= $targetvalue) && (is_null($max_value_b) || preg_replace('/([^0-9.])/i', '',$max_value_b) >= $targetvalue) && !(is_null($min_value_b) && is_null($max_value_b))) $values[] = $value_for_b;
if((is_null($min_value_a) || preg_replace('/([^0-9.])/i', '',$min_value_a) <= $targetvalue) && (is_null($max_value_a) || preg_replace('/([^0-9.])/i', '',$max_value_a) >= $targetvalue) && !(is_null($min_value_a) && is_null($max_value_a))) $values[] = $value_for_a;
?>
As it turns out, your items are formatted with spaces, thus when converted to a float for interpretation it only looked at the first set of numbers. preg_replace('/([^0-9.])/i', '', $var) removes anything non-numerical. (This is quite computationally expensive, mind)

How to test if $value is $num +-3 [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
php if integer between a range?
Let's say $num = 5; How do I test if $value is anything in between +-3 of $num. In other words, how can I test if $value is equal to any of these values 2,3,4 5 6,7,8
Two possible ways to do it:
$num - 3 <= $value && value <= $num + 3
abs($num - $value) <= 3
$mid = 5;
$range = 3;
$inRange = ($myval>=$mid-$range && $myval<=$mid+$range) ? TRUE : FALSE;
UPDATE
I started throwin' out bass, she started throwin' back mid-range.
if ($num - 3 <= $value && $value <= $num + 3)
if ($value<=$num+3 && $value>=$num-3)
echo "$value is between +-3 of $num";
else
echo "$value is outside +-3 of $num";
try this:
$dif1 = $num - 3;
$dif2 = $num + 3;
if($dif1 <= $value){
if($dif2 <= $value){
echo "Your number in between +-3";
}
}
There is nothing big logic in this if you know the $num value take two variable $min and $max
set $min = $num - 3
set $max = $num + 3
and then with condition check your value..
$value > $min && $value < $max

Evaluating multiple expressions to determine the range of a numeric variable in php

Sorry if the title is confusing.
I have several string expressions in an array like these:
var1 <= 6 && var1 > 3
var1 > 2
var1 > 4.5
var2 < 22.5
var2 >= 14.25
var2 < 16
How can I go about evaluating all of the expressions to determine:
var1 min
var1 max
var2 min
var2 max
I understand that with the expressions that are not "or equal to" I won't be able to get an exact value. That is alright.
You're trying to do simple linear programming. SimplexInPHP implements linear programming in PHP, which you could use. See it in action here.
The other option is to implement a solution yourself. Use split() to split each inequality into tokens. For each variable, compute the min/max by starting off with the range [-inf, inf] and update it for each inequality. If the operator begins with < then update max to max(cur_max, value); otherwise update min to min(cur_min, value).
You'll also have to keep track of whether the end-points are inclusive or exclusive. This can be done with booleans is_min_inclusive and is_max_inclusive. A new end-point is inclusive if the operator ends in =, otherwise it's to exclusive. Be sure to handle the case where you have x < 1 and x <= 1 (in both orders), which should result in x < 1.
<?php
$string = "var1 <= 6 && var1 > 0 && var2 >= 4 && var2 < 200";
//creates an array with the key 'name' and 'min OR 'max'
function parseExpression($expression){
$parts = preg_split("|( )+|", $expression,3,PREG_SPLIT_NO_EMPTY);
$result = array('name'=>$parts[0]);
switch ($parts[1]){
case '<':
$parts[2]-=1;
//NO BREAK <x same as <=(x-1)
case '<=':
$result['max'] = $parts[2];
break;
case '>':
$parts[2]+=1;
//NO BREAK >x same as >=(x+1)
case '>=':
$result['min'] = $parts[2];
break;
default:
throw new Exception("format not supported");
}
return $result;
}
$expressions = explode("&&", $string);
$vars = array();
foreach ($expressions as $expression){
$parsed = parseExpression($expression);
$name = array_shift($parsed);
foreach ($parsed as $key => $value){
if (array_key_exists($key,$vars[$name])){
switch ($key){
case 'min':
$vars[$name][$key] = min($vars[$name][$key],$value);
break;
case 'max':
$vars[$name][$key] = max($vars[$name][$key],$value);
break;
default:
}
throw new Exception("format not supported");
}
else{
$vars[$name][$key] = $value;
}
}
}
var_dump($vars);
?>
<?php
$arr = array("var1 <= 6",
"var1 > 2",
"var1 > 4.5",
"var2 < 22.5",
"var2 >= 14.25",
"var2 < 16");
function find_min_max($arr, $variable) {
$min = '-inf';
$max = 'inf';
while (list($i, $v) = each($arr)) {
list($var, $rel, $value) = preg_split('/\s+/', $v);
if ($var != $variable) continue;
if ($rel == "<" || $rel == "<=") {
if ($value < $max)
$max = $value;
}
else if ($rel == ">" || $rel == ">=") {
if ($value > $min)
$min = $value;
}
}
return array($min, $max);
}
list($min, $max) = find_min_max($arr, "var1");
echo "var1 $min - $max \n";
list($min, $max) = find_min_max($arr, "var2");
echo "var3 $min - $max \n";
?>
So in your example, you'd expect the minimum var1 to be >4.5 and the max to be <=6? Have you considered changing your data structure?
If, for example, your data structure looked something like this:
$limits=array('lte'=>array(6), 'lt'=>array(),'gte'=>array(),'gt'=>(2,4.5);
then parsing becomes trivial. The max of the gt and gte arrays would be the minimum value, with > or >= depending on which array it came from. The minimum of lt and lte arrays would be the max value.
I guess...
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.min.php
In the example they show nummeric string expressions (so not only casted floats or ints)

Categories