Thursday, April 13, 2006

controlled 'crements

Have you ever wanted to create a function that would increment an integer position by a certain number as long as it didn't go over a max or under a minimum?

Here's a function I wrote recently that does this:


/**
* Increment or decrement a given position by a change amount within rules
*
* @author Richard AT d2p.us
* @param int $position
* @param int $change_by
* @param int $max
* @param int $min
* @param string $incOrDec
*/
function incrementDecrement(&$position, $change_by, $max, $min = 1, $incOrDec = "inc"){
if ($incOrDec == "inc"){
if (($position + $change_by ) <= $max){
$position = $position + $change_by;
}else {
$position = $max;
}
}else {
if (($position - $change_by ) >= $min){
$position = $position - $change_by;
}else{
$position = $min;
}
}
}


Of course, this doesn't return anything, I have it changing the original position because I pass by reference, but change this to suite you.

0 Comments:

Post a Comment

<< Home