Compare numbers in an array with a range of values

908 views Asked by At

I want to compare 2 arrays. But in the case of numbers, I want to compare within a specified range.

For example we go compare 3 vars : sex , color eyes and height

In the case of height, if for example people have 1,70 of height and in other array I have 1,75, I don't get results, because it only shows exact matches with that data.

I would like to show results when the other array is in the range 1,70 to 1,79

<?php
$arra_1=array("woman","blue","1,70");
$array_2=array("woman","brown","1,71");
$result=array_intersect($array_1,$array_2);
print_r($result);
?>

In these conditions with array_intersect(), it shows me only 1 result because the only common value is "woman," but if I could compare a range of heights between 1,70 to 1,80 it would give me 2 results.

How I can compare numbers in two arrays between minimum and maximum ranges?

2

There are 2 answers

1
miken32 On

Rather than use array_intersect() which just checks for equality, you can use array_uintersect() which uses a function you create to compare the arrays. It should return zero if values are considered equal.

function loose_comp($a, $b) {
    // text will be compared as usual
    if (!is_numeric($a) || !is_numeric($b)) {
        return $a === $b;
    }
    // I check for a difference of ±10%
    // you can do whatever check you want
    if ($a <= $b * 1.1 && $a >= $b * 0.9) {
        return 0;
    }
    return 1;
}

$array_1 = ["woman","blue","1,70"];
$array_2 = ["woman","brown","1,71"];
$result = array_uintersect($array_1, $array_2, "loose_comp");
print_r($result);

This gives me this output:

Array
(
    [0] => woman
    [2] => 1.70
)

(Note I had to change decimal point to . for it to work on my system.)

0
Andreas On

As I see it you are overcomplicating it.
Just loop the array and look at the values.

$heightspan = substr($array_1[2],0,3);
$sex = $array_1[0];

foreach($array_2 as $arr){
    if($arr[0] == $sex && substr($arr[2],0,3) == $heightspan){
        $result[] = $arr;
    }
}
print_r($result);

https://3v4l.org/Qg3Uh