Find the next "less than" value in an array

2

I have the following array and I need to find the next smaller value than the one defined in $valor :

$seq = array(500, 490, 430, 370, 350, 240, 100, 90);
$n_seq = count($seq);
$valor = 400; // ASSUME DIFERENTES VALORES
    if ($valor > $seq[0]){
        $encontrado = $seq[0];
        } else {
        for ($i = $n_seq; $seq[$i] > $valor; $i--) {
        $encontrado = $seq[($i+1)];}
        }
echo "Valor atribuído: ".$valor;
echo "<br>";
echo "Valor encontrado: ".$encontrado;

Example: If $valor assumes the value 630, the answer would be 500.

If $valor takes the value 500, the answer would be 490.

If $valor is set to 240, the answer would be 100.

Problem: I do not know if I can chain if() next to for() , because depending on the values $valor assumes I have a Undefined offset error with Undefined variable .

Could someone please help me?

    
asked by anonymous 05.04.2014 / 14:05

1 answer

3

Here's a suggestion:

  • Sort the array using sort () with option 1 to do numeric sort
  • look for the first number that is greater than or equal to $valor (alternatively you could search for the previous value, ie the last one to be less than $valor )

PHP:

$seq = array(500, 490, 430, 370, 350, 240, 100, 90);
sort($seq, 1);
$n_seq = count($seq);

$valor = 400; // ASSUME DIFERENTES VALORES
$encontrado = '';
for($i = 0; $i < $n_seq; $i++){
    if ($seq[$i] >= $valor){ // ou usar somente ">"
    $encontrado = $i == 0 ? $seq[$i] : $seq[$i - 1]; 
    break;

    } 
}
if ($encontrado == '' && $valor > end($seq)) $encontrado = end($seq);
if ($encontrado == '' && $valor < $seq[0]) $encontrado = $seq[0];

echo "Valor atribuido: ".$valor;
echo "<br>";
echo "Valor encontrado: ".$encontrado;
    
05.04.2014 / 14:24