<?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:#ffffff" ';
$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;
?>
Dieses PHP Snippet soll in erster Linie als Beispiel und Anregung für eigene Bemühungen dienen.
Gerne darf man es für Projekte aller Art benutzen.
Möchte jemand das Snippet also solches in ähnlicher oder anderer Form veröffentlichen ist ein kleiner Hinweis auf simplecontent.net nicht zuviel verlangt oder Herr Koch?
Für die Abwesenheit von Fehlern kann natürlich keine Gewähr gegeben werden.