Jump to content

[SOLVED] Exploring a range of numbers


cs1h

Recommended Posts

Hi,

 

Does anyone know of a way to check for numbers that fit within a certain range. The best way to explain what I mean is with an example.

 

If I have the number 5.5 I want to be able to compare it with a group of numbers and find any numbers between 4.5 and 6.5 (i.e. plus or minus 1) in that group.

 

Any help will be appreciated.

 

Cs1h

Link to comment
https://forums.phpfreaks.com/topic/171248-solved-exploring-a-range-of-numbers/
Share on other sites

Hi,

 

I was hoping to find a way so that if I had the list of numbers

1.8,3.9,45.2,35.1

it would be able to look through the longer string like this

11.1,15.2,1.5,4.8,45.3,35.6,77.1,12.2

With a variance of +/- 1 it would be able to identify that the pattern exists in the string

11.1,15.2,1.5,4.8,45.3,35.6,77.1,12.2

 

Thanks for the help so far,

Cs1h

Sure you can:

<?php
$deviance = 1;

$string1 = '1.8,3.9,45.2,35.1';
$string2 = '11.1,15.2,1.5,4.8,45.3,35.6,77.1,12.2';

$array1 = explode(',', $string1);
$array2 = explode(',', $string2);

$matches = array();

foreach ($array1 as $item1) {
$upperBound = $item1 + $deviance;
$lowerBound = $item1 - $deviance;

foreach ($array2 as $item2) {
	if ($item2 >= $lowerBound && $item2 <= $upperBound) {
		$matches[] = (float) $item2;
	}
}
}

var_dump($matches);

 

Output:

array(4) {
  [0]=>
  float(1.5)
  [1]=>
  float(4.
  [2]=>
  float(45.3)
  [3]=>
  float(35.6)
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.