How to search for a value between a past range

0

I have to find if the value ( 5.55 for example) exists in an array and know which range in that array is, and bring me the range id.

I had a test and it seemed to be working and when I entered a value 0 (zero) already broke my logic, then I made a change and it works, but then I do not know if there is any way better to do.

<?php
    $precisao = 0.000001;

    $matriz = array(
            array('id'=> 1 , 'vl_inicial' => 0.00, 'vl_final', 19.55),
            array('id'=> 2 , 'vl_inicial' => 19.56, 'vl_final', 28.23),
            array('id'=> 3 , 'vl_inicial' => 30.00, 'vl_final', 100.00)
        );

    $valor = 5.55;

    foreach($matriz as $m) {

        if( in_array($valor, range($m['vl_inicial'], $m['vl_final'])) || 
            (($valor - $m['vl_inicial']) > $precisao) AND (($valor - $m['vl_final']) <= $precisao) )
        {
            return $m['id'];
        }            
    }

    return FALSE;
    
asked by anonymous 17.12.2014 / 17:06

1 answer

3

From PHP documentation , more specifically in the description of the parameter $step :

  

Description

array range ( mixed $low , mixed $high [, number $step ] )
     

Create an array containing a range of elements

     

Parameters   [...]

     

step

     

If the step parameter is specified, it will be used as the increment between the elements of the sequence. step must be a positive integer. If   not specified, step will have value equal to 1.

That is, you are using the function range and you are expecting a different result.

To check if the value is within a range, a simple if with both ends is sufficient.

<?php

$valor = 5.55;

$matriz = array(
        array('id'=> 1 , 'vl_inicial' => 0.00, 'vl_final', 19.55),
        array('id'=> 2 , 'vl_inicial' => 19.56, 'vl_final', 28.23),
        array('id'=> 3 , 'vl_inicial' => 30.00, 'vl_final', 100.00)
);

foreach($matriz as $intervalo) {

    if( ($valor >=  $intervalo['vl_inicial']) && ($valor <= $intervalo['vl_final']) )
    {
        // return $m['id'];
    }            
}
    
17.12.2014 / 17:15