Jump to content

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)
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.