views:

69

answers:

5

Is there such a function in PHP or MySQL?

function check($lower,$val, $upper)
{
if ($val>$lower && $val<$upper)
{
return $val;
}
if ($val<=$lower)
{
return $lower;
}

if ($val>=$upper)
{
return $upper;
}
}
+3  A: 

I don't believe so, but there is min() and max():

function check($lower, $val, $upper) {
    return min(max($lower, $val), $upper);
}

Cheers, Tom

Tom Bartel
A: 

I don't know of one but you could use min() and max(). By the way - it looks like what you're really asking for is the midpoint of three integers. Either way, the code would look like:

function midValue($lowerBound, $upperBound, $value) {
   return (min($upperBound, max($lowerBound, $myValue)));
}
Chris Williams
A: 
<?php

echo(check(20, 40, 50));

function check($lower,$val, $upper){
if ($val>$lower && $val<$upper){
return $val; }
else if ($val<=$lower){
return $lower;}
else if ($val>=$upper){
return $upper;}
}

Is valid php that works. I don't see much of a problem...

CodeJoust
The problem is that it is too many lines of code for too little functionality. If you use 6 lines of code for every function where one line would suffice, your programs are going to be unmanageably bloated soon.
Tom Bartel
+2  A: 

Can't think of a single function for this in MySQL, but this idiom would do the same:

GREATEST( @lower, LEAST( @val, @upper ) )
martin clayton
A: 

It may work as you intended, adding a touch of documentation, preferebly in Docbloc type format is nice to clue people in quiclkly on what you are doing. It adds a professional touch.

I guess Tom factorised your code for you.

A thumb-up for the MYSQL answer, nice! :)

stef