Oft hat man eine "weiter zum nächsten" bzw. "zurück zum vorherigen"-Eintrag Funktionalität.
Also eine Art (Um-)Blätterfunktion.
Diese Funktion sorgt dafür, dass man den gültigen Wertebereich nicht verlassen kann.
Dabei gibt es drei unterschiedliche Arten wie mit Werten ausserhalb des Bereiches verfahren wird.
Schaut Euch dazu einfach das Beispiel an.
<?php
function KeepWithinBounds($n, $low, $high, $bool = NULL)
{
// catch false parameter values
$debug = array_shift(debug_backtrace());
if (!is_numeric($n) || !is_numeric($low) || !is_numeric($high)):
trigger_error(__FUNCTION__.'() parameters #1-#3 are expected to be numeric in line '.$debug['line'], E_USER_ERROR);
return false;
endif;
if ($low > $high):
trigger_error(__FUNCTION__.'() $low parameter expected to be less or equal than $high parameter in line '.$debug['line'], E_USER_WARNING);
return false;
endif;
// determine what type of handling should be used
$type = 'CONTINUE';
if ($bool == false){
$type = 'FIXED_REVERSE';
}
if ($bool === NULL){
$type = 'FIXED';
}
switch($type):
case 'FIXED':
if ( $n < $low){
$n = $low;
}
if ( $n > $high){
$n = $high;
}
break;
case 'FIXED_REVERSE':
if ( $n < $low){
$n = $high;
}
if ( $n > $high){
$n = $low;
}
break;
case 'CONTINUE':
$d = $high - $low + 1;
while($n < $low){
$n += $d;
}
while($n > $high){
$n -= $d;
}
break;
default:
die ('FATAL ERROR in function <strong>'.__FUNCTION__.'()</strong>');
break;
endswitch;
return $n;
}
$rows = '';
$min = 2;
$max = 9;
for($i=-10;$i< 20;$i++){
$tmp = array(
$i,
KeepWithinBounds($i, $min, $max),
KeepWithinBounds($i, $min, $max,true),
KeepWithinBounds($i, $min, $max,false),
);
$style = ($i %2)
? ' style="background-color:#cce1e1" '
: ' style="background-color:#ffcccc" ';
$rows .= '<tr'.$style.'><td>'.join('</td><td>', $tmp).'</td></tr>';
}
echo <<< EOT
<table border="1" style="text-align:right;">
<tr><th>i</th><th>NULL</th><th>true</th><th>false</th></tr>
$rows
</table>
EOT;
?>