Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

check And Count Value over php array

i am trying to count the number of times value is between 2 elements of array
first array is the company grade

Comps Esg Grades

$arr1 = [1,2,3,9,5,6,20,35,9,10];

the second array is the compere array

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Final Compare

$arr2 = [0,2.2,10.4,20,30,44,60];

what i would like to achieve is
the number of times company is between to elements of array

first company grade is 1. so i am iterating over the arr2
like so to check if the value of 1 is between the elements
[0] and [1] [1] and [2] [2] and [3]
and so on

if the value is true so i add 1
when i am checking the next company value in this case its 2
so i need to add 1 to the previews check so the result should be 2
because i have 2 grade that in between 0 and 2.2

this is my code:

//Comps Esg Grades
$arr1 = [1,2,3,9,5,6,20,35,9,10];
//Final Compare
$arr2 = [0,1.7,10.4,20,30,44,60];
$countArray = [];

foreach ($arr1 as $r){
   
    foreach ($arr2 as $keyMain =>  $r2){
        $countArray[$keyMain] = 0;
       
    }
}

foreach ($arr1 as $r){
  
    foreach ($arr2 as $key =>  $r2){
        if($r2 > $r && $r2 < $arr2[$key + 1]){
            $currentVal = $countArray[$key];
            $countArray[$key] = $currentVal + 1;
         }
        
    }
}

and this is the result

   Array
   (
    [0] => 0
    [1] => 1
    [2] => 8
    [3] => 8
    [4] => 9
    [5] => 10
    [6] => 0
   )

>Solution :

I would run first on the ranges array ($arr2) and for each of those find how many items from the first array fit. The exact details though really depends on the expected result.

//Comps Esg Grades
$arr1 = [1,2,3,9,5,6,20,35,9,10];
//Final Compare
$arr2 = [0,1.7,10.4,20,30,44,60];
$countArray = [];


for ($i=0; $i<count($arr2)-1; $i++) {
    $min = $arr2[$i];
    $max = $arr2[$i+1];
    $countArray[$i] = 0;

    for ($j=0; $j<count($arr1); $j++) {
        
        if ($arr1[$j] >= $min && $arr1[$j] <= $max) {
            $countArray[$i]++;
        }
    }
}

print_r($countArray);

Output:

Array
(
    [0] => 1
    [1] => 7
    [2] => 1
    [3] => 1
    [4] => 1
    [5] => 0
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading