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?