Ensure that a specific value lies within a specific range.
<?php
/*
Ever had to code something that relies on a numeric value being inside a specific range of minimum and maximum values?
I was coding some image functions and I found myself writing code like this:
if ($color['red'] < 0)
{
$color['red'] = 0;
}
else if ($color['red'] > 255)
{
$color['red'] = 255;
}
if ($color['green'] < 0)
{
$color['green'] = 0;
}
else if ($color['green'] > 255)
{
$color['green'] = 255;
}
if ($color['blue'] < 0)
{
$color['blue'] = 0;
}
else if ($color['blue'] > 255)
{
$color['blue'] = 255;
}
Seems like tremendous amount of code for something that simpler so I quickly made a simple (but handy!) function to handle this mess for me.
*/
function Between($number, $minimum = null, $maximum = null)
{
if (is_null($min) === false)
{
$min = floatval($min);
if ($value < $min)
{
$value = $min;
}
}
if (is_null($max) === false)
{
$max = floatval($max);
if ($value > $max)
{
$value = $max;
}
}
return $value;
}
// You can use it like this:
$color['red'] = Between($color['red'], 0, 255);
$color['green'] = Between($color['green'], 0, 255);
$color['blue'] = Between($color['blue'], 0, 255);