3
I have the following array and need to locate the next smallest value that 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
assumes the value 500, the answer would be 490.
If $valor
assumes the value 240, the answer would be 100.
Problem: I don’t know if I can chain if()
next to a for()
, depending on the values that $valor
assumes an error of Undefined offset
with Undefined variable
.
Someone could help me?
You mean, "the highest value in the array that is less than $value"? What do you expect in return if $value is 80? The array elements will always be sorted or this was a particular case of your example?
– user4552